简体   繁体   English

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

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

I'm writing the loader for webpack that preprocess arrow functions in html to classic functions. 我正在编写webpack加载程序,将html中的箭头功能预处理为经典功能。 I'm going to use it with knockoutjs. 我将它与淘汰赛一起使用。 For preprocessing I use this package 对于预处理,我使用此程序包

For now I have 现在我有

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

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

  var template = rewrite(str);

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

It works fine when I directly preprocess .html file. 当我直接预处理.html文件时,它可以正常工作。 But when using other loader in the chain (eg require("knockout-arrows!jade!./file.jade") ) it becomes broken, since jade loader also returns string with "module.exports = '<h1>example</h1>'" . 但是当在链中使用其他加载器(例如require("knockout-arrows!jade!./file.jade") )时,它就会损坏,因为jade也返回带有"module.exports = '<h1>example</h1>'"

So my question is how to cut this 'module.exports' and get the plain string? 因此,我的问题是如何切割此“ module.exports”并获取纯字符串? Surely, i can use regex, but I think it's wrong. 当然,我可以使用正则表达式,但是我认为这是错误的。

Sorry for kind of noob question. 对不起,菜鸟问题。

In the chat it turned out that you're using jade-static-loader , which exports a string containing a module export containing the HTML. 在聊天中,事实证明您使用的是jade-static-loader ,它会导出一个字符串,该字符串包含一个包含HTML的模块导出。

In other words, this is the string that the loader is getting: 换句话说,这是加载程序获取的字符串

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

To extract the HTML, you can use eval() (which in this case should be safe), and subsequently run the replacement code: 要提取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);
};

What about using val-loader in between the jade loader and yours? 在玉器和您的玉器之间使用val-loader怎么办? I had this same problem trying to use haml and dust loaders: 我在尝试使用hamldust装载机时遇到了同样的问题:

Changed from: 更改自:

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

to: 至:

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

From webpack's documentation: 从webpack的文档中:

val: Executes code as module and consider exports as JavaScript code val:将代码作为模块执行,并将导出视为JavaScript代码

and per the loader documentation itself: 并根据加载程序文档本身:

This loader is also useful if you want to provide data for another loader 如果要为另一个加载器提供数据,此加载器也很有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM