使用同一模板文件与HtmlWebpackPlugin和EJS?

时间:2019-07-31 04:32:54

标签: javascript webpack ejs

在HtmlWebpackPlugin中,<%-表示输出转义,而<%=表示输出转义。在EJS中,情况恰恰相反。是否可以将它们交换为HtmlWebpackPlugin或EJS?

2 个答案:

答案 0 :(得分:1)

这是我使用的自定义加载程序:

// 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})();
    }}`;
};

答案 1 :(得分:0)

因此,文档说:

  

“使用lodash模板提供您自己的模板,或使用您自己的加载器”

与EJS相比,我们可以看到它正在改变。快速更新可以实现您的目标:

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

在此处了解更多信息:https://stackoverflow.com/a/35546804/398939

现在,将它们应用于插件,看看代码https://github.com/jantimon/html-webpack-plugin/blob/5acac51da302451cca5b33f305d8d26c7cc2b87f/lib/loader.js#L26,您可以像这样传递它们:

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