webpackwebpack-dev-serverwebpack-plugin

Webpack - Copying Files In Development and Production


I wrote a plugin that does something similar to copy-webpack-plugin, but provides some extended functionalities that I need. Essentially it simply copies files from src to dist and performs some operations on them.

It works fine when I run a production build, but in my development build, since i'm using devServer and everything is in memory, this doesn't work.

How can I solve this?


Solution

  • As it turns out, the solution is quite simple. All you need to do is use compliation.assets to add more files, instead of something manual like fs.writeFile. This will work regardless of whether you're serving the files from memory or from the file system.

    For example, the code below will create a file in path/to/file.ext with Hello World! in it:

    class MyCoolPlugin {
        apply(compiler) {
            compiler.hooks.emit.tapAsync('MyCoolPlugin', (compilation, done) => {
                compilation.assets['path/to/file.ext'] = {
                    source: () => 'Hello World!', // The file's content
                    size: () => 10 // Should be the byte size of the content
                };
                done();
            });
        }
    }