Joey Yi Zhao
Joey Yi Zhao

Reputation: 42418

`html-loader` overwrite `HtmlWebpackPlugin` `<%= %>` expression

I am using HtmlWebpackPlugin in webpack and below is its configuration:

new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'index.html',
        inject: 'body',
        sdk: '/mylib.js'
      })

In my html I define the script tag as:

<script src="<%= htmlWebpackPlugin.options.sdk %>"></script>

webpack will replace the <%= htmlWebpackPlugin.options.sdk %> with /mylib.js. However it doesn't work once I add the html-loader plugin as below:

{
          test: /\.html$/,
          use: [
            {
              loader: 'html-loader',
              options: {
                attrs: 'img:src'
              }
            }
          ]
        }

The reason I use html-loader is to parse the img src tag on html file. But it conflicts with HtmlWebpackPlugin <%= ... %> expression. How can I make both of them work?

Upvotes: 3

Views: 2702

Answers (3)

You need to combine three steps.

First, you need HtmlWebpackPlugin. as indicated by https://stackoverflow.com/a/56264384/9363857

Second, you activate html-loader. This leads to the strange result of having a line like

module.exports=.....

in the middle of your html (replacing the require), which is not really what you want.

So, third, you need to translate this back to html, for which you need to add an extract-loader. As in:

test: /\.(html)$/, use:  [ 'extract-loader',  { loader: 'html-loader' } ] 

Upvotes: 0

Aggie
Aggie

Reputation: 139

The easiest solution i found for this is to rename your template with .ejs extention. This will kick in html-webpack-plugin (as it's an fallback ejs-loader), and then after it process all the <%= %> it will kick in the html-loader.

This way the html-webpack-plugin will running first and then followed by html loader.

new HtmlWebpackPlugin({
    filename: 'index.html',
    template: 'index.html.ejs',  // don't forget to rename the actual file
    inject: 'body',
    sdk: '/mylib.js'
  })

Upvotes: 1

JohMun
JohMun

Reputation: 446

I would give the property ignoreCustomFragments of html-loader a try. According to the docs, you can pass it as an option and the loader ignores some parts, depending on a RegExp: ignoreCustomFragments: [/<%=.*%>/]

Upvotes: 0

Related Questions