Skip to content

Commit

Permalink
feat: update & optimizate webpack4 😊 #24
Browse files Browse the repository at this point in the history
  • Loading branch information
nicejade committed May 12, 2018
1 parent 6102450 commit 5a4fb4d
Show file tree
Hide file tree
Showing 5 changed files with 286 additions and 76 deletions.
9 changes: 7 additions & 2 deletions build/utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const path = require('path')
const config = require('../config')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

exports.assetsPath = function (_path) {
var assetsSubDirectory = process.env.NODE_ENV === 'production'
Expand Down Expand Up @@ -31,7 +32,11 @@ exports.cssLoaders = function (options) {
})
}

return ['vue-style-loader'].concat(loaders)
if (options.extract) {
return [MiniCssExtractPlugin.loader].concat(loaders)
} else {
return ['vue-style-loader'].concat(loaders)
}
}

// http://vuejs.github.io/vue-loader/en/configurations/extract-css.html
Expand All @@ -58,4 +63,4 @@ exports.styleLoaders = function (options) {
})
}
return output
}
}
4 changes: 2 additions & 2 deletions build/webpack.base.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ function createHappyPlugin (id, loaders) {
module.exports = {
entry: {
app: './src/main.js',
vendor: ['lodash']
lodash: ['lodash'],
element: ['element-ui']
},
mode: env === 'production' ? 'production' : 'development',
output: {
Expand Down Expand Up @@ -134,7 +135,6 @@ module.exports = {
externals: {
// 'element-ui': 'ElementUI',
// 'vue': 'Vue',
// 'lodash': '_',
'babel-polyfill': 'window'
},
plugins: [
Expand Down
168 changes: 100 additions & 68 deletions build/webpack.prod.conf.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
const fs = require('fs')
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
Expand All @@ -10,11 +9,11 @@ const HtmlWebpackPlugin = require('html-webpack-plugin')
const AddAssetHtmlPlugin = require('add-asset-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 SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin')
const loadMinified = require('./load-minified')
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin')
const BabiliWebpackPlugin = require('babili-webpack-plugin')
const Jarvis = require('webpack-jarvis')

const env = process.env.NODE_ENV === 'testing'
Expand All @@ -28,86 +27,46 @@ const webpackConfig = merge(baseWebpackConfig, {
extract: true
})
},

devtool: config.build.productionSourceMap ? '#source-map' : false,
// @desc: Documenttion: https://webpack.js.org/configuration/performance/

performance: {
// Given an asset is created that is over 250kb;false | "error" | "warning"(Default)
hints: 'warning',
// The default value is 250000 (bytes).
maxEntrypointSize: 307200, // (300kb)
maxEntrypointSize: 500000, // (300kb)
// This option controls when webpack emits a performance hint based on individual asset size. The default value is 250000 (bytes).
maxAssetSize: 307200
maxAssetSize: 500000
},

output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},

optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: config.build.productionSourceMap // set to true if you want JS source maps
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSAssetsPlugin({})
],
// @desc: Documentation:https://www.webpackjs.com/plugins/split-chunks-plugin/
splitChunks: {
// chunks: "initial","async"和"all"分别是:初始块,按需块或所有块;
chunks: 'async',
// (默认值:30000)块的最小大小
minSize: 25600,
// (默认值:1)分割前共享模块的最小块数
minChunks: 1,
// (缺省值5)按需加载时的最大并行请求数
maxAsyncRequests: 9,
// (默认值3)入口点上的最大并行请求数
maxInitialRequests: 9,
// webpack 将使用块的起源和名称来生成名称: `vendors~main.js`,如项目与"~"冲突,则可通过此值修改,Eg: '-'
automaticNameDelimiter: '~',
// cacheGroups is an object where keys are the cache group names.
name: true,
cacheGroups: {
// 设置为 false 以禁用默认缓存组
default: {
minChunks: 2,
// 默认组的优先级为负数,以允许任何自定义缓存组具有更高的优先级(默认值为0)
priority: -20,
// 选项 reuseExistingChunk 允许重复使用现有的块,而不是在模块完全匹配时创建新的块
reuseExistingChunk: true,
},
commons: {
name: "commons",
chunks: "initial",
minChunks: 2,
maxInitialRequests: 5
},
vendor: {
name: "vendor",
test: /[\\/]node_modules[\\/]/,
priority: -10
},
style: {
name: 'style',
test: /\.(scss|css)$/,
priority: 0,
enforce: true
}
}
}
// runtimeChunk: true, adds an additonal chunk to each entrypoint containing only the runtime.
/*
@desc: Setting optimization.runtimeChunk to true adds an additonal chunk to each entrypoint containing only the runtime.
The value single instead creates a runtime file to be shared for all generated chunks.
@reference: https://doc.webpack-china.org/plugins/split-chunks-plugin/#optimization-runtimechunk
*/
// runtimeChunk: {
// name: 'manifest'
// }
},

plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),

/*
@desc: A faster uglifyjs plugin.(用来替代 Webpack `uglifyjs-webpack-plugin`)
@reference: https://github.com/gdborton/webpack-parallel-uglify-plugin
*/
new ParallelUglifyPlugin({
cacheDir: '.cache/',
uglifyJS: {
Expand All @@ -117,14 +76,62 @@ const webpackConfig = merge(baseWebpackConfig, {
},
compress: {
warnings: false,
drop_console: true
drop_console: true,
collapse_vars: true,
reduce_vars: true
}
}
}),

// extract css into its own file
new MiniCssExtractPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),

// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSAssetsPlugin({}),

// A Webpack Plugin for Babili - A babel based minifier
// https://www.npmjs.com/package/babili-webpack-plugin
new BabiliWebpackPlugin(),

// @desc: Documentation:https://www.webpackjs.com/plugins/split-chunks-plugin/
new webpack.optimize.SplitChunksPlugin({
// chunks: "initial","async"和"all"分别是:初始块,按需块或所有块;
chunks: 'all',
// (默认值:30000)块的最小大小
minSize: 50000,
// (默认值:1)分割前共享模块的最小块数
minChunks: 1,
// (缺省值5)按需加载时的最大并行请求数
maxAsyncRequests: 8,
// (默认值3)入口点上的最大并行请求数
maxInitialRequests: 8,
// webpack 将使用块的起源和名称来生成名称: `vendors~main.js`,如项目与"~"冲突,则可通过此值修改,Eg: '-'
automaticNameDelimiter: '~',
// cacheGroups is an object where keys are the cache group names.
name: true,
cacheGroups: {
// 设置为 false 以禁用默认缓存组
default: false,
element: {
name: 'element',
test: /[\\/]node_modules[\\/]element-ui[\\/]/,
chunks: 'initial',
// 默认组的优先级为负数,以允许任何自定义缓存组具有更高的优先级(默认值为0)
priority: -10
},
lodash: {
name: 'lodash',
test: /[\\/]node_modules[\\/]lodash[\\/]/,
chunks: 'initial',
// 默认组的优先级为负数,以允许任何自定义缓存组具有更高的优先级(默认值为0)
priority: -10
}
}
}),

// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
Expand All @@ -138,28 +145,30 @@ const webpackConfig = merge(baseWebpackConfig, {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
// @reference: https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via splitChunks
chunksSortMode: 'dependency',
serviceWorkerLoader: `<script type="text/javascript">${loadMinified(path.join(__dirname,
'./service-worker-prod.js'))}</script>`
}),

new AddAssetHtmlPlugin({
filepath: path.resolve(__dirname, 'dist/*.dll.js')
}),
// copy custom static assets

// copy custom static assets (已在 build.js 中通过 Shell 做了,所以可不用此插件;)
// new CopyWebpackPlugin([
// {
// from: path.resolve(__dirname, '../static'),
// to: config.build.assetsSubDirectory,
// ignore: ['.*']
// }
// ]),

/*
@desc: service worker caching, More detailed configuration:
https://github.com/goldhand/sw-precache-webpack-plugin
@reference: https://github.com/goldhand/sw-precache-webpack-plugin
*/
new SWPrecacheWebpackPlugin({
cacheId: 'your-app-name',
Expand All @@ -168,22 +177,45 @@ const webpackConfig = merge(baseWebpackConfig, {
minify: true,
stripPrefix: 'dist/'
}),

new LodashModuleReplacementPlugin(),
/*
@desc: limit minChunkSize through MinChunkSizePlugin
@reference: https://webpack.js.org/plugins/min-chunk-size-plugin/
*/
new webpack.optimize.MinChunkSizePlugin({
minChunkSize: 25600 // Minimum number of characters (25kb)
minChunkSize: 50000 // Minimum number of characters (25kb)
}),

/*
@desc: AggressiveSplittingPlugin 可以将 bundle 拆分成更小的 chunk;
直到各个 chunk 的大小达到 option 设置的 maxSize,它通过目录结构将模块组织在一起
@reference: https://doc.webpack-china.org/plugins/aggressive-splitting-plugin/
@but: 由于 HtmlWebpackPlugin 插件中的错误,此方法在启用时不起作用;
具体可参见:https://github.com/jantimon/html-webpack-plugin/issues/446
*/
// new webpack.optimize.AggressiveSplittingPlugin({
// minSize: 10000,
// maxSize: 500000
// }),

/*
@desc: 编译之后,您可能会注意到某些块太小 - 创建更大的HTTP开销,那么您可以处理像这样;
@reference: https://webpack.js.org/plugins/limit-chunk-count-plugin/
*/
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 10 // Must be greater than or equal to one
// minChunkSize: 1000
})
}),

// 在编译出现错误时,使用 NoEmitOnErrorsPlugin 来跳过输出阶段;
new webpack.NoEmitOnErrorsPlugin(),

/*
@desc: 提升代码在浏览器中的执行速度: 作用域提升(scope hoisting);
@reference: https://doc.webpack-china.org/plugins/module-concatenation-plugin/
*/
new webpack.optimize.ModuleConcatenationPlugin()
]
})

Expand Down Expand Up @@ -212,8 +244,8 @@ if (config.build.bundleAnalyzerReport) {

if (config.build.bundleIntelligentDashboard) {
webpackConfig.plugins.push(new Jarvis({
port: 1337 // optional: set a port.
port: 1337
}))
}

module.exports = webpackConfig
module.exports = webpackConfig
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
"precommit-msg": "echo 'Pre-commit checks...' && exit 0",
"analyz": "NODE_ENV=production npm_config_report=true npm run build",
"clean-commit": "git checkout --orphan latest_branch && git add -A && git commit -am 'style: clean past commit history 😊' && git branch -D master && git branch -m master && git push -f origin master",
"commitmsg": "validate-commit-msg",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
"generate-sitemap": "node build/generate-sitemap.js"
},
Expand Down Expand Up @@ -64,6 +63,7 @@
"babel-preset-env": "^1.2.1",
"babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.22.0",
"babili-webpack-plugin": "^0.1.2",
"chai": "^3.5.0",
"chalk": "^1.1.3",
"chromedriver": "^2.27.2",
Expand Down Expand Up @@ -128,7 +128,6 @@
"svgxuse": "^1.1.16",
"sw-precache-webpack-plugin": "^0.11.4",
"uglify-es": "^3.3.9",
"uglifyjs-webpack-plugin": "^1.2.5",
"url-loader": "^0.5.7",
"vue-loader": "^11.0.0",
"vue-style-loader": "^2.0.0",
Expand Down
Loading

0 comments on commit 5a4fb4d

Please sign in to comment.