如何将加载程序输出转换为字符串

How to cast loader output to a string

我的 webpack 配置如下所示:

var webpack = require('webpack');

module.exports = {
    // ..
    module: {
        loaders: [
            // ..
            {
                test: /\.scss$/,
                loaders: ['css', 'sass']
            }
        ]
    }
};

我想要require('./my-style.scss')到return一个字符串。但是,现在它正在 returning 一个 Array 对象:

0: Array[3]
    0: 223
    1: "html,↵body,↵ol,↵ul,↵li,↵p { margin: 0; padding: 0; }↵"
    2: ""
    length: 3
i: (modules, mediaQuery) { .. }
length: 1
toString: toString()

我可以将 require 语句转换为字符串 (require('./my-style.scss').toString()),尽管我会用 webpack 为我做这件事。

如何修改加载程序定义以生成字符串作为最终输出?

我写了一个小型加载程序,可以将对象转换为字符串,to-string

它是一个简单的加载器,像模块一样执行内容并将输出转换为字符串:

/**
 * @see https://github.com/webpack/webpack/wiki/Loader-Specification
 */
module.exports = function (content) {
    return 'module.exports = ' + JSON.stringify(this.exec(content, this.resource).toString());
};