【问题标题】:Using the same template file with HtmlWebpackPlugin and EJS?使用与 HtmlWebpackPlugin 和 EJS 相同的模板文件?
【发布时间】:2019-12-08 12:40:15
【问题描述】:

在 HtmlWebpackPlugin 中,<%- 表示输出转义,<%= 表示输出未转义。在 EJS 中,情况正好相反。是否可以将它们换成 HtmlWebpackPlugin 或 EJS?

【问题讨论】:

标签: javascript webpack ejs


【解决方案1】:

所以,文档说:

"使用 lodash 模板提供你自己的模板,或者使用你自己的加载器"

我们可以看到与 EJS 相比,改变它的是 lodash。快速更新可以实现您所追求的:

_.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
})

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-10-04
      • 1970-01-01
      • 2014-09-08
      • 2017-09-02
      • 2016-08-08
      • 2015-10-17
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多