简体   繁体   中英

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. 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. 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>'" .

So my question is how to cut this 'module.exports' and get the plain string? 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.

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:

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? I had this same problem trying to use haml and dust loaders:

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:

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

and per the loader documentation itself:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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