在 webpack 构建过程后连接 JS 文件

Rob*_*bin 3 javascript ecmascript-6 webpack

我正在尝试在webpack 构建过程之后连接两个 js 文件。目标是提供一个包含 ES6 模块和遗留代码的单个 js 文件。

已经尝试过像webpack-concat-files-plugin这样的插件但没有成功。这对我来说很有意义,因为执行插件时输出文件不存在。

另一个想法是在afterCompile挂钩中执行一个小脚本,该脚本处理两个文件的串联。这是做类似事情的常见方法还是还有其他方法可以实现目标?

感谢您的帮助。


基本示例:

module.exports = {
  entry: {
    app: 'app.js',
    legacy: [
      'legacy-1.js',
      'legacy-2.js', 
      // ...
    ]
  },
  output: {
    filename: path.join('dist/js', '[name].js'),
  }
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*bin 6

按照建议解决了这个问题:

文件合并WebpackPlugin.js

const fs = require('fs');

class FileMergeWebpackPlugin {
  constructor({ files, destination, removeSourceFiles }) {
    this.files = files;
    this.destination = destination;
    this.removeSourceFiles = removeSourceFiles;
  }

  apply(compiler) {
    compiler.hooks.afterEmit.tap('FileMergeWebpackPlugin', () => {
      const fileBuffers = [];

      this.files
        .filter(file => fs.existsSync(file))
        .forEach(file => fileBuffers.push(fs.readFileSync(file)))

      fs.writeFileSync(this.destination, fileBuffers.concat(), { encoding: 'UTF-8' })

      if (this.removeSourceFiles) {
        this.files.forEach(file => fs.unlinkSync(file));
      }
    });
  }
}

module.exports = FileMergeWebpackPlugin;
Run Code Online (Sandbox Code Playgroud)

webpack.config.js

const FileMergeWebpackPlugin = require('./FileMergeWebpackPlugin');

module.exports = {
  entry: {
    app: 'app.js',
    legacy: [
      'legacy-1.js',
      'legacy-2.js',
    ]
  },
  output: {
    filename: path.join('dist/js', '[name].js'),
  },
  plugins: [
    new FileMergeWebpackPlugin({
      destination: 'dist/js/bundle.js',
      removeSourceFiles: true,
      files: [
        'dist/js/app.js',
        'dist/js/legacy.js',
      ]
    })
  ]
}
Run Code Online (Sandbox Code Playgroud)

最终我会将其作为 npm 包发布,届时我将更新帖子