[英]WebPack: problem when compiling JS files in html
我在使用 Webpack 时遇到问题。 I'm using a JS file to call an API, but this API should be called only in escudos.html, but when I do the Webpack build, the JS file calls the API int both (index.html, escudos.html). I only want that the./src/js/teams.js call API when I am in the escudos.html, not in in both (index.html, escudos.html) HTML.
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
index: './src/js/index.js',
teams: './src/js/teams.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].bundle.js',
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
}),
new HtmlWebpackPlugin({
filename: 'escudos.html',
template: './src/escudos.html',
}),
],
devServer: {
static: './dist',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: { loader: 'babel-loader' },
},
],
},
};
出于某种原因,我的 webpacked 文件 index.html 也有team.js
问题(和解决方案)在 HtmlWebpackPlugin 中。 默认情况下,HtmlWebpackPlugin 会在每个页面中注入所有条目。
我能想到三个解决方案:
inject: false
: 这将禁用<script>
标签自动注入模板。 您必须使用正确的 src 手动编写<script>
标记。 (pss:不要)chunks
:指定要包含在此模板中的条目。 EG:(解决 OP 问题,在大多数情况下您将需要/使用什么) new HtmlWebpackPlugin({ template: "./src/index.html", chunks: ["index"] }), new HtmlWebpackPlugin({ template: "./src/escudos.html", chunks: ["teams"] })
exclude
:注入除此数组中指定的条目之外的所有条目。 例如new HtmlWebpackPlugin({ template: "./src/test.html", exclude: ["index"] })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.