I am having a problem while working with 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' },
},
],
},
};
for some reason my webpacked file index.html has the teams.js too
CodePudding user response:
The problem (and the solution) is in HtmlWebpackPlugin. HtmlWebpackPlugin injects all entries in every page by default.
There exists three solutions I can think of:
inject: false
: This disables auto injection of<script>
tags into the templete. You have to manually write<script>
tag(s) with the proper src. (Psss: don't)chunks
: specifiy which entries you want to be included for this template. E.G: (Solves the OP problem, what you will need/use in most cases)new HtmlWebpackPlugin({ template: "./src/index.html", chunks: ["index"] }), new HtmlWebpackPlugin({ template: "./src/escudos.html", chunks: ["teams"] })
exclude
: inject all entries except the ones specified in this array. E.Gnew HtmlWebpackPlugin({ template: "./src/test.html", exclude: ["index"] })