【问题标题】:Concatenate JS files after webpack build process在 webpack 构建过程之后连接 JS 文件
【发布时间】:2021-04-27 02:50:09
【问题描述】:

我正在尝试在 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'),
  }
}

【问题讨论】:

    标签: javascript webpack ecmascript-6


    【解决方案1】:

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

    FileMergeWebpackPlugin.js

    const fs = require('fs');
    
    class FileMergeWebpackPlugin {
      constructor({ files, destination, removeSourceFiles }) {
        this.files = files;
        this.destination = destination;
        this.removeSourceFiles = removeSourceFiles;
      }
    
      apply(compiler) {
        const fileBuffers = [];
    
        compiler.hooks.afterEmit.tap('FileMergeWebpackPlugin', () => {
          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;
    

    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',
          ]
        })
      ]
    }
    

    最终我会将它作为一个 npm 包发布,当我这样做时会更新帖子

    【讨论】:

      【解决方案2】:

      是的。

      您可以创建自己的插件,在emit 钩子中激活 - 这个钩子的参数是编译。你可以从这个对象中获取你想要连接的块,并使用连接的值创建一个新块(或者只是将一个添加到另一个)

      【讨论】:

        猜你喜欢
        • 2017-04-05
        • 2017-08-16
        • 2020-12-04
        • 2016-12-22
        • 1970-01-01
        • 2016-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多