1

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

1 Answer 1

1

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:

  1. 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)
  2. 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"]
    })
    
  3. exclude: inject all entries except the ones specified in this array. E.G
    new HtmlWebpackPlugin({
        template: "./src/test.html",
        exclude: ["index"]
    })
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.