Search code examples
javascripthtmlwebpackhtml-webpack-plugin

How to exclude html-webpack-plugin templates from raw-loader in webpack


I have a very large project that uses two webpack bundles to support an older and newer version of the website. The config for one uses a raw-loader to handle html files. It looks like this:

this.configModern = {
  entry: 'modern',
  output: {
    filename: 'bundled-[name].[chunkhash].js',
    path: path.join(__dirname, '/Scripts/bundled/')
  },
  module: {
    rules: [
        {
            test: /\.html$/,
            use: [
                'raw-loader'
            ]
        },
    ]
  },
  plugins: [
    new CommonsChunkPlugin({
      name: 'vendor-modern',
      minChunks: function (module) {
        return module.context
          && module.context.includes('node_modules');
      }
    }),
    new webpack.ProvidePlugin({
      'window.jQuery': 'jquery'
    }),
    new HtmlWebpackPlugin({
      filename: 'bundle_modern_dev.html',
      template: './Views/Shared/WebpackTemplates/devTemplate.html',
      inject: false,
    }),
  ],
};

And here is my devTemplate.html

<% for (var js in htmlWebpackPlugin.files.js) { %>
<script src="/Scripts/bundled/<%= htmlWebpackPlugin.files.js[js] %>"></script>
<% } %>

My problem is that the raw-loader causes webpack to copy the contents of my devTemplate.html to the output file.

How do I exclude the template file so that it uses the default ejs loader for html-webpack-plugin, and doesn't use the raw-loader.

EDIT:

webpack is version 2.3.1

html-webpack-plugin is version 3.2.0


Solution

  • This is how we can exclude files or folders in Webpack

    module: {
        rules: [
            {
                test: /\.html$/,
                exclude:/WebpackTemplates/,   /* Add this line */
                use: [
                    'raw-loader'
                ]
            },
        ]
      },
    

    I added the folder containing the templates (WebpackTemplates) to the exclude option of raw-loader

    This means that it will ignore all the files inside that folder.

    You can add multiple folders/folder to exclude option using regex.