title: Webpack Plugin: How to add dynamically a Module to the main Chunk?
body: <p>I'm working on a Webpack plugin that basically looks for a <code>css</code> assets inside the chunks, when it founds such asset, applies on it some <code>postCSS</code> plugin that returns 2 outputs, the one should continue to be extracted using <code>Extract-Text-Plugin</code> and the other output should become a <strong>new module</strong> inside the <strong>chunk</strong> that injects it to the head on runtime.</p>
  
  <p>The only part that I'm not managed to implement is the part that creates a <strong>new module</strong> inside <strong>existing</strong> Chunk. There is some pointers / ideas?</p>
  
  <p>I managed to create a <strong>new chunk</strong> out of it but without webpack wrappers, that means that I'm not able to support HMR for that piece of css and load it lazily. </p>
  
  <pre><code>class ExtractTPAStylePlugin {
    constructor(options) {
      this._options = Object.assign({
        pattern: [
          /"\w+\([^\)]+\)"/
        ]
      }, options);
    }
  
    extract(compilation, chunks) {
      const promises = [];
  
      chunks.forEach((chunk) =&gt; {
        promises.push(
          chunk.files
            .filter(fileName =&gt; fileName.endsWith('.css'))
            .map(file =&gt; postcss([extractStyles(this._options)])
              .process(compilation.assets[file].source(), {from: file, to: file})
              .then((result) =&gt; {
                compilation.assets[file] = new RawSource(result.css);
  
                const filename = file.replace('.css', fileSuffix);
                const newChunk = new Chunk(filename);
                newChunk.files = [filename];
                newChunk.ids = [];
                compilation.chunks.push(newChunk);
                const extractedStyles = `(${addStylesTemplate})()`
                  .replace('__CSS__', JSON.stringify(result.extracted))
                  .replace('__ID__', file);
                compilation.assets[filename] = new OriginalSource(extractedStyles);
              }))
        );
      });
  
      return Promise.all(promises);
    }
  
    apply(compiler) {
      compiler.plugin('compilation', (compilation) =&gt; {
        compilation.plugin('optimize-chunk-assets', (chunks, callback) =&gt; {
          this.extract(compilation, chunks)
            .then(() =&gt; callback())
            .catch(callback);
        });
      });
    }
  }
  
  module.exports = ExtractTPAStylePlugin;
  </code></pre>