如何在 webpack 加载器中 trim 输出 'module.exports' 并获取纯字符串?

How to trim out 'module.exports' in webpack loader and get plain string?

我正在为 webpack 编写加载程序,将 html 中的箭头函数预处理为经典函数。我打算将它与 knockoutjs 一起使用。 对于预处理,我使用这个 package

现在我有

var rewrite = require('knockout-arrows');

module.exports = function (str) {
  if (this.cacheable) {
      this.cacheable();
  }

  var template = rewrite(str);

  return "module.exports = '"  + template + "'";
};

当我直接预处理 .html 文件时它工作正常。但是当在链中使用其他加载程序时(例如 require("knockout-arrows!jade!./file.jade")),它会被破坏,因为 jade 加载程序也 returns 带有 "module.exports = '<h1>example</h1>'".

的字符串

所以我的问题是如何剪切这个 'module.exports' 并得到纯字符串?当然,我可以使用正则表达式,但我认为这是错误的。

抱歉,有点菜鸟问题。

在聊天中发现您正在使用 jade-static-loader,它导出一个包含模块导出的字符串,其中包含 HTML.

换句话说,这是加载程序正在获取的 string

"module.exports = '...HTML string...'"

要提取 HTML,您可以使用 eval()(在这种情况下应该是安全的),然后 运行 替换代码:

var rewrite = require('knockout-arrows');

module.exports = function (str) {
  if (this.cacheable) {
      this.cacheable();
  }
  var html     = eval(str);
  var template = rewrite(html);

  // Export the replaced HTML as another string:
  return "module.exports = "  + JSON.stringify(template);
};

在 jade loader 和你的之间使用 val-loader 怎么样?我在尝试使用 hamldust 加载器时遇到了同样的问题:

更改自:

{ test: /\.js\.dust\.haml/, loader: 'dust-loader!haml-haml' }

至:

{ test: /\.js\.dust\.haml/, loader: 'dust-loader!val-loader!haml-haml' }

来自 webpack 的文档:

val: Executes code as module and consider exports as JavaScript code

根据加载程序文档本身:

This loader is also useful if you want to provide data for another loader