gloriaJun / til

Lessoned Learned
3 stars 0 forks source link

Custom webpack entry file order #110

Open gloriaJun opened 3 years ago

gloriaJun commented 3 years ago

Version

webpack v4

Scenario

아래와 같이 정의된 entry 파일들에 대해 index.html 에 주입되는 순서를 정의하고 싶은 경우

  entry: {
    'a': resolve('src/lib/a.ts'),
    'b': resolve('src/lib/b.ts'),
    'app': resolve('src/index.js'),
  },

HtmlWebPackPlugin 플러그인의 chunksSortMode 를 정의하여 해결할 수 있다.

// <rootDir>/build/utils/index.js

exports.packageSort = function(packages) {
  return function sort(chunk1, chunk2) {
    const getName = (chunk) => chunk.names[0].split('~')[0];

    const order1 = packages.indexOf(getName(chunk1));
    const order2 = packages.indexOf(getName(chunk2));

    console.log('### check --- chunk1', chunk1.names[0], order1);
    console.log('### check --- chunk2', chunk2.names[0], order1);

    if (order1 > order2) {
      return 1;
    } else if (order1 < order2) {
      return -1;
    } else {
      return 0;
    }
  };
};
// <rootDir>/build/webpack.config.js
const HtmlWebPackPlugin = require('html-webpack-plugin');
//...SKIP
const utils = require('./utility')
//...SKIP

    new HtmlWebPackPlugin({
      template: `public/template.html`,
      filename: `index.html`,
      chunksSortMode: utils.packageSort(['a', 'b', 'app']),
    }),

//...SKIP

Reference