From d6cb2cbc79c6592a9655b60769b6760f6855d86b Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Fri, 18 Aug 2017 11:47:56 +0430 Subject: [PATCH] improve CommonsChunkPlugin inspired by zeit next --- lib/builder/builder.js | 3 +++ lib/builder/webpack/client.config.js | 18 ++++++++++++++++-- lib/common/options.js | 2 +- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/lib/builder/builder.js b/lib/builder/builder.js index 5bb25d15b3..b9fbabcfdc 100644 --- a/lib/builder/builder.js +++ b/lib/builder/builder.js @@ -236,6 +236,9 @@ export default class Builder extends Tapable { this.options.router.extendRoutes(templateVars.router.routes, r) } + // Make routes accessible for other modules and webpack configs + this.routes = templateVars.router.routes + // -- Store -- // Add store if needed if (this.options.store) { diff --git a/lib/builder/webpack/client.config.js b/lib/builder/webpack/client.config.js index a5617ebd0b..2b55d80070 100644 --- a/lib/builder/webpack/client.config.js +++ b/lib/builder/webpack/client.config.js @@ -31,18 +31,32 @@ export default function webpackClientConfig () { config.entry.vendor.push('vuex') } config.entry.vendor = config.entry.vendor.concat(this.options.build.vendor) + // Extract vendor chunks for better caching + const _this = this config.plugins.push( new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: this.options.build.filenames.vendor, - minChunks (module) { + minChunks (module, count) { + // In the dev we use on-demand-entries. + // So, it makes no sense to use commonChunks based on the minChunks count. + // Instead, we move all the code in node_modules into each of the pages. + if (_this.options.dev) { + return false + } + + // Total pages + const totalPages = _this.routes.length + // A module is extracted into the vendor chunk when... return ( // If it's inside node_modules /node_modules/.test(module.context) && // Do not externalize if the request is a CSS file - !/\.(css|less|scss|sass|styl|stylus)$/.test(module.request) + !/\.(css|less|scss|sass|styl|stylus)$/.test(module.request) && + // Used in at-least 1/2 of the total pages + (totalPages <= 2 ? count >= totalPages : count >= totalPages * 0.5) ) } }) diff --git a/lib/common/options.js b/lib/common/options.js index 5167188986..0f86776561 100755 --- a/lib/common/options.js +++ b/lib/common/options.js @@ -166,7 +166,7 @@ Options.defaults = { filenames: { css: 'common.[contenthash].css', manifest: 'manifest.[hash].js', - vendor: 'vendor.[chunkhash].js', + vendor: 'common.[chunkhash].js', app: 'app.[chunkhash].js', chunk: '[name].[chunkhash].js' },