webpackpug-loader

How to select what bundles a certain html page will use?


the project

I have a project where the website view is written using Pug, then compiled to HTML.

index.pug ---> index.html

Because I want the project to have more than one page, I have got this, as well:

about.pug ---> about.html

Now, each of these pages have entries, in webpack.config.js:

{
  entry: {
    index: ['scripts/index.ts'],
    about: ['scripts/about.ts'],
  }
}

I don't think it's good to have a single bundle for both, because there's imported modules which are unique to each page entry (that is: if I know what I'm talking about).

the problem

When the HTML is generated, html-webpack-plugin automatically injects both bundles in both pages, which is worse then what I just explained.

How can I tell it to inject just the bundle I want?

ps: I tried including each of them, manually in the *.pug files. Although, generated bundle filenames have hashes, in order to achieve cache busting.


Solution

  • Before writing this question, I spent three hours searching for a solution.

    Although, right after submitting it, I refreshed search page and found the solution.

    It's about chunks.

    You pass a hash of options to html-webpack-plugin, in which there's a property named "chunks". This property can take an array of string, with the names of desired entries.

    
    {
      plugins: [
    
        new HtmlWebpackPlugin({
          template: 'views/index.pug',
          scriptLoading: 'defer',
          filename: 'index.html',
          chunks: [
            "index"
          ]
        }),
    
        new HtmlWebpackPlugin({
          template: 'views/about.pug',
          scriptLoading: 'defer',
          filename: 'about.html',
          chunks: [
            "about"
          ]
        }),
    
        new HtmlWebpackPugPlugin()
      ]
    }
    

    Sorry for the trouble.