Delete or not create a file for each entry in webpack

I hacked together a SuppressEntryChunksPlugin (code below) that skips output of these useless bundles, if you tell it which bundles will be useless. Use it in your webpack.config.js like this:

var SuppressEntryChunksPlugin = require('./SuppressEntryChunksPlugin');
...
  entry: {
    'app': './src/app.ts',
    'css': './src/css/main.unique.scss',
    'index': './src/index.unique.html',
  },
  plugins: [
    // don't output the css.js and index.js bundles
    new SuppressEntryChunksPlugin(['css', 'index'])
  ]

Disclaimers: It works for me together with extract-loader and file-loader to extract the css/html from the entries and write the files into the output. I haven't tested it with ExtractTextPlugin. (It does work with webpack-dev-server. And it seems to successfully suppress external sourcemaps if you're using them. I've used it with both Webpack 1.13 and 2.2.1.)

// SuppressEntryChunksPlugin.js

function SuppressEntryChunksPlugin(options) {
  if (typeof options === 'string') {
    this.options = {skip: [options]};
  } else if (Array.isArray(options)) {
    this.options = {skip: options};
  } else {
    throw new Error("SuppressEntryChunksPlugin requires an array of entry names to strip");
  }
}

SuppressEntryChunksPlugin.prototype.apply = function(compiler) {
  var options = this.options;

  // just before webpack is about to emit the chunks,
  // strip out primary file assets (but not additional assets)
  // for entry chunks we've been asked to suppress
  compiler.plugin('emit', function(compilation, callback) {
    compilation.chunks.forEach(function(chunk) {
      if (options.skip.indexOf(chunk.name) >= 0) {
        chunk.files.forEach(function(file) {
          // delete only js files.
          if (file.match(/.*\.js$/)) {
            delete compilation.assets[file];
          }
        });
      }
    });
    callback();
  });
};

module.exports = SuppressEntryChunksPlugin;

Also, I'm whatever the opposite of "webpack expert" is, so there's almost certainly a better way to do this. (Perhaps someone would like to turn this into a real, published webpack plugin, with tests and whatnot?)

Tags:

Webpack