3

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?

3 Answers 3

1

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'
  })
Sign up to request clarification or add additional context in comments.

2 Comments

With this method, html-loader will not insert image names/links anymore.
@Mecanik we could still import images, using ejs syntax, example: <img src="<%= require('../images/image-name.jpg') %>" />
0

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: [/<%=.*%>/]

1 Comment

Webpack 5: ValidationError: Invalid options object. HTML Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'ignoreCustomFragments'. These properties are valid: object { preprocessor?, sources?, minimize?, esModule? }
0

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' } ] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.