访问 Webpack 插件中的文件内容

jok*_*arl 5 webpack

我正在尝试编写一个 Webpack 插件,它采用 webpack 生成的 CSS 并为其添加自定义前缀。我已经启动并运行并连接到emit编译器阶段,但我找不到一种优雅的方式来访问我需要的文件内容。

下面是我到目前为止所得到的所有代码,基于编写插件示例。我如何访问资产的内容?日志记录compilation.assets['main.css']仅显示对源的脏访问。

PrefixCssPlugin.prototype.apply = function(compiler) {
  compiler.plugin('after-compile', function(compilation) {
    console.log(new RawSource(compilation.assets['main.css']));
  });

  compiler.plugin('emit', (compilation, callback) => {
    let prefixedCssContent = '';
    for (const filename in compilation.assets) {
      for (const pattern in filePatterns) {
        if (filePatterns[pattern].test(filename)) {
          console.log(`${filename} matched ${filePatterns[pattern]}`);
          console.log(JSON.stringify(compilation.assets[filename]));

            // I want to access the contents of the matched file here, and pass it
            // to another module that will handle the prefixing.
/*           prefixedCssContent = cssPrefixer(
            compilation.assets[filename],
            cssPrefix, 
            shouldPrefixElements); */
        }
      }
    }

    // Insert this list into the webpack build as a new file asset:
    compilation.assets['prefixed.css'] = {
      source: function() {
        return prefixedCssContent;
      },
      size: function() {
        return prefixedCssContent.length
      }
    };

    callback();
  });
};
Run Code Online (Sandbox Code Playgroud)

jok*_*arl 3

太快了,不利于我自己。文档明确指出要阅读源代码,我只是没有读得足够好。这就是我一直在寻找的东西。现在一切正常,只剩下一些调整和错误处理了。