Access file content in a Webpack plugin

Viewed 1695

I'm trying to write a Webpack plugin that takes the CSS that webpack generates and prefix it with a custom prefix. I'm up and running and hooked in to the emit phase of the compiler, but I can't find an elegant way to access the file contents that I need.

Below is all the code I've got so far, based on the example Writing a Plugin. How can I access the contents of the asset? Logging compilation.assets['main.css'] only shows me dirty access to the source.

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();
  });
};
1 Answers

Too quick for my own good. The docs clearly say to read the source code, I just didn't read it well enough. Here's what I was looking for. It all works now, just some tweaking and error handling left.

Related