1

I’m trying to use DefinePlugin with html-loader. I’m using interpolation in html-loader, and trying to use values from DefinePlugin in the interpolated expressions.

This works when I load into HtmlWebpackPlugin, or when html-loader is the only loader used for the html file, but if I load from html-loader into extract-loader, DefinePlugin doesn’t appear to do its replacement before extract-loader tries to process the file data.

Example:

src/index.html:

<!DOCTYPE html>
<html>
<head>
    <title>${ TITLE }</title>
</head>
<body>
</body>
</html>

webpack.config.js:

const { DefinePlugin } = require('webpack');

module.exports = {
  mode: 'none',
  entry: [
    "./src/index.html"
  ],
  module: {
    rules: [
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: {
              interpolate: true
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new DefinePlugin({
      TITLE: JSON.stringify('My page title')
    }),
  ]
};

This works as expected, and when observing the output main.js, the interpolated part of the HTML has been replaced with the My page title value of TITLE.

Of course, I want to extract this HTML to a separate file using extract-loader and file-loader. Taking this one step at a time, I first add extract-loader to process the output from html-loader, as follows:

...
    rules: [
      {
        test: /\.html$/,
        use: [
+++       "extract-loader",
          {
            loader: "html-loader",
            options: {
              interpolate: true
            }
          }
        ]
      }
    ]
...

This results in a build failure:

ERROR in ./src/index.html
Module build failed (from ./node_modules/extract-loader/lib/extractLoader.js):
NonErrorEmittedError: (Emitted value instead of an instance of Error) ReferenceError: TITLE is not defined

My expectation is that since files are processed by loaders sequentially, TITLE should have already been replaced by the time extractLoader.js is ready to touch it. What am I missing here?

NReilingh
  • 1,730
  • 17
  • 32

0 Answers0