From 1889cdec6eeee264bb762229b527fa99eccfa6a7 Mon Sep 17 00:00:00 2001 From: Pan Date: Wed, 8 Aug 2018 14:20:01 +0800 Subject: [PATCH] refine NamedChunksPlugin --- build/webpack.prod.conf.js | 27 +++++++++++++++++---------- package.json | 1 + 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/build/webpack.prod.conf.js b/build/webpack.prod.conf.js index 42feb1f5..1e8f5bed 100644 --- a/build/webpack.prod.conf.js +++ b/build/webpack.prod.conf.js @@ -11,21 +11,17 @@ const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin') const UglifyJsPlugin = require('uglifyjs-webpack-plugin') -const crypto = require('crypto'); - function resolve(dir) { return path.join(__dirname, '..', dir) } -function createHash(data) { - const length = 8 - const hash = crypto.createHash('md5').update(data).digest("hex") - return hash.slice(0, length) -} - const env = require('../config/' + process.env.env_config + '.env') +// For NamedChunksPlugin +const seen = new Set(); +const nameLength = 4; + const webpackConfig = merge(baseWebpackConfig, { mode: 'production', module: { @@ -76,11 +72,22 @@ const webpackConfig = merge(baseWebpackConfig, { //`runtime` must same as runtimeChunk name. default is `runtime` inline: /runtime\..*\.js$/ }), + // keep chunk.id stable when chunk has no name new webpack.NamedChunksPlugin(chunk => { if (chunk.name) { - return chunk.name + return chunk.name; + } + const modules = Array.from(chunk.modulesIterable); + if (modules.length > 1) { + const hash = require("hash-sum"); + const joinedHash = hash(modules.map(m => m.id).join("_")); + let len = nameLength; + while (seen.has(joinedHash.substr(0, len))) len++; + seen.add(joinedHash.substr(0, len)); + return `chunk-${joinedHash.substr(0, len)}`; + } else { + return modules[0].id; } - return createHash(Array.from(chunk.modulesIterable, m => m.id).join('_')) }), // keep module.id stable when vender modules does not change new webpack.HashedModuleIdsPlugin(), diff --git a/package.json b/package.json index f8a91591..738a663b 100644 --- a/package.json +++ b/package.json @@ -85,6 +85,7 @@ "eslint-plugin-html": "4.0.5", "file-loader": "1.1.11", "friendly-errors-webpack-plugin": "1.7.0", + "hash-sum": "^1.0.2", "html-webpack-plugin": "^4.0.0-alpha", "husky": "0.14.3", "lint-staged": "7.2.0",