Search code examples
javascriptnpmwebpackfrontendwebpack-5

How to packed another js file using Webpack5?


I am a newcomer to webpack.

I have 2 javascript files and I want to use one as the entry file. For another I don't want all the html use it, I'll use it in some specify files.

For exmaple, as you can see the file structure below ,main.js is my entry file. And there is another js file called 123.js. I expect that 1.html uses both main.js and 123.js. However, the ./2.html only need `./main.js

File Structure:

./main.js
./123.js
./1.html
./2.html

How to implement this? Thanks.


Solution

  • You can use HtmlWebpackPlugin

    Your webpack configuration could look something like this:

    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      entry: {
        main: './main.js',
        oneTwoThree: './123.js'
      },
      plugins: [
        new HtmlWebpackPlugin({
          filename: '1.html',
          chunks: ['main', 'oneTwoThree']
        }),
        new HtmlWebpackPlugin({
          filename: '2.html',
          chunks: ['main']
        })
      ],
      output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
      },
    };