Leo Jiang
Leo Jiang

Reputation: 26183

Using the same template file with HtmlWebpackPlugin and EJS?

In HtmlWebpackPlugin, <%- means output escaped and <%= means output unescaped. In EJS, it's the opposite. Is it possible to swap them for either HtmlWebpackPlugin or EJS?

Upvotes: 8

Views: 1223

Answers (2)

Leo Jiang
Leo Jiang

Reputation: 26183

Here's the custom loader I used:

// From html-webpack-loader/lib/loader.js

const _ = require('lodash');

module.exports = function (source) {
  const allLoadersButThisOne = this.loaders.filter(loader => loader.normal !== module.exports);
  // This loader shouldn't kick in if there is any other loader (unless it's explicitly enforced)
  if (allLoadersButThisOne.length > 0) {
    return source;
  }
  // Skip .js files (unless it's explicitly enforced)
  if (/\.js$/.test(this.resourcePath)) {
    return source;
  }

  // The following part renders the template with lodash as a minimalistic loader
  //
  const template = _.template(source, {
    interpolate: /<%-([\s\S]+?)%>/g,
    escape: /<%=([\s\S]+?)%>/g,
    variable: 'data',
  });
  // Use __non_webpack_require__ to enforce using the native nodejs require
  // during template execution
  return `var _ = __non_webpack_require__(${JSON.stringify(require.resolve('lodash'))});
    module.exports = function (templateParams) { with(templateParams) {
      return (${template.source})();
    }}`;
};

Upvotes: 1

Ahmed Nuaman
Ahmed Nuaman

Reputation: 13261

So, the docs say:

"supply your own template using lodash templates, or use your own loader"

And we can see it's lodash that's changing it compared to EJS. A quick update can achieve what you're after:

_.templateSettings = {
  interpolate: /<%([\s\S]+?)%>/g,
  escape: /<%=([\s\S]+?)%>/g,
  evaluate: /<%-([\s\S]+?)%>/g
};

Read more here: https://stackoverflow.com/a/35546804/398939

Now to apply these into the plugin, having had a look at the code: https://github.com/jantimon/html-webpack-plugin/blob/5acac51da302451cca5b33f305d8d26c7cc2b87f/lib/loader.js#L26, you can pass them in like so:

new HtmlWebpackPlugin({
  title: 'My App',
  filename: 'assets/admin.html',
  interpolate: /<%([\s\S]+?)%>/g,
  escape: /<%=([\s\S]+?)%>/g,
  evaluate: /<%-([\s\S]+?)%>/g
})

Upvotes: 0

Related Questions