WebPack:在 html 中编译 JS 文件时出现问题
WebPack: problem when compiling JS files in html
我在使用 Webpack 时遇到问题。我正在使用 JS 文件调用 API,但是这个 API 应该只在 escudos.html 中调用,但是当我进行 Webpack 构建时,JS 文件调用 API int 两者 (index.html, escudos.html)。我只希望 ./src/js/teams.js 在我处于 escudos.html 时调用 API,而不是在两者 (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 也有 teams.js
问题(和解决方案)在 HtmlWebpackPlugin 中。默认情况下,HtmlWebpackPlugin 会在每个页面中注入所有条目。
我能想到三种解决方案:
inject: false
:这将禁用自动将 <script>
标签注入到模板中。您必须使用正确的 src 手动编写 <script>
标签。 (嘘:不要)
chunks
:指定要包含在该模板中的条目。 E.G:(解决OP问题,大多数情况下你会need/use)
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"]
})
我在使用 Webpack 时遇到问题。我正在使用 JS 文件调用 API,但是这个 API 应该只在 escudos.html 中调用,但是当我进行 Webpack 构建时,JS 文件调用 API int 两者 (index.html, escudos.html)。我只希望 ./src/js/teams.js 在我处于 escudos.html 时调用 API,而不是在两者 (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 也有 teams.js
问题(和解决方案)在 HtmlWebpackPlugin 中。默认情况下,HtmlWebpackPlugin 会在每个页面中注入所有条目。
我能想到三种解决方案:
inject: false
:这将禁用自动将<script>
标签注入到模板中。您必须使用正确的 src 手动编写<script>
标签。 (嘘:不要)chunks
:指定要包含在该模板中的条目。 E.G:(解决OP问题,大多数情况下你会need/use)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"] })