Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - Concatenate JS files after webpack build process

I'm trying to concatenate two js files after the webpack build process. The goal is to provide a single js file with the ES6 modules and the legacy code in it.

Already tried plugins like webpack-concat-files-plugin without success. Which makes sense to me, because the output files are not there when the plugin gets executed.

Another thought would be a small script executed in the afterCompile hook, which handles the concatenation of the two files. Is this the common way to do something like this or are there other ways to achieve the goal?

Thanks for your help.


Basic example:

module.exports = {
  entry: {
    app: 'app.js',
    legacy: [
      'legacy-1.js',
      'legacy-2.js', 
      // ...
    ]
  },
  output: {
    filename: path.join('dist/js', '[name].js'),
  }
}
question from:https://stackoverflow.com/questions/65848510/concatenate-js-files-after-webpack-build-process

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solved this as suggested:

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

Eventually i will release this as a npm package, will update the post when i do so


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...