Webpack - 在开发和生产中复制文件

Webpack - Copying Files In Development and Production

我写了一个插件,其功能类似于 copy-webpack-plugin,但提供了一些我需要的扩展功能。本质上,它只是将文件从 src 复制到 dist 并对其执行一些操作。

当我 运行 生产版本时它工作正常,但在我的开发版本中,因为我使用 devServer 并且一切都在内存中,所以这不起作用。

我该如何解决这个问题?

事实证明,解决方案非常简单。您需要做的就是使用 compliation.assets 添加更多文件,而不是像 fs.writeFile 这样的手动操作。无论您是从内存还是从文件系统提供文件,这都会起作用。

例如,下面的代码将在 path/to/file.ext 中创建一个包含 Hello World! 的文件:

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