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

Leo*_*ang 8 javascript ejs webpack

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

Leo*_*ang 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})();
    }}`;
};
Run Code Online (Sandbox Code Playgroud)