使用DllPlugin能够很大程度提升webpack的构建速度,可是有几点不注意的话会使得打包的体积较大。html
如下以react的配置来讲明一下(webpack3)node
const path = require('path'); const webpack = require('webpack'); const DllPlugin = require('webpack/lib/DllPlugin'); module.exports = { entry: { vendor: ['react', 'react-dom', 'react-router'] }, output: { path: path.resolve(__dirname, '../public/static/dll'), filename: '[name].js', library: '[name]' }, devtool: 'inline-source-map', plugins: [ new DllPlugin({ filename: '[name].js', name: '[name]', path: path.resolve(__dirname, '../public/static/dll', '[name].manifest.json'), //描述生成的manifest文件 }), new webpack .optimize .UglifyJsPlugin({ compress: { warnings: false, //删除无用代码时不输出警告 drop_console: true, //删除全部console语句,能够兼容IE collapse_vars: true, //内嵌已定义但只使用一次的变量 reduce_vars: true, //提取使用屡次但没定义的静态值到变量 }, output: { beautify: false, //最紧凑的输出,不保留空格和制表符 comments: false, //删除全部注释 } }) ] }
能够发现,仅仅是 'react', 'react-dom', 'react-router' 这三个就有三百多k,是否是太大了一点!!!react
在plugins中加入 webpack
plugins: [ ... new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), ]
从新打包,能够发现,打包的体积一会儿降到了 143 kB git
resolve: { alias: { 'react': path.resolve(__dirname, '../node_modules/react/cjs/react.production.min.js'), 'react-dom': path.resolve(__dirname, '../node_modules/react-dom/cjs/react-dom.production.min.js'), 'react-router': path.resolve(__dirname, '../node_modules/react-router/umd/react-router.min.js'), } },
从新打包, 发现打包的体积为 123 kB ,减小了20k。
关于dll打包中,使用声明 production 和 使用 alias 处理路径 能够大幅减小包的体积。github
如下说一下, dll 打包具体怎么作web
相似这样npm
const path = require('path'); const webpack = require('webpack'); const DllPlugin = require('webpack/lib/DllPlugin'); module.exports = { entry: { vendor: ['react', 'react-dom', 'react-router'] }, resolve: { alias: { 'react': path.resolve(__dirname, '../node_modules/react/cjs/react.production.min.js'), 'react-dom': path.resolve(__dirname, '../node_modules/react-dom/cjs/react-dom.production.min.js'), 'react-router': path.resolve(__dirname, '../node_modules/react-router/umd/react-router.min.js'), } }, output: { path: path.resolve(__dirname, '../public/static/dll'), filename: '[name].js', library: '[name]' }, devtool: 'inline-source-map', plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new DllPlugin({ filename: '[name].js', name: '[name]', path: path.resolve(__dirname, '../public/static/dll', '[name].manifest.json'), //描述生成的manifest文件 }), new webpack .optimize .UglifyJsPlugin({ compress: { warnings: false, //删除无用代码时不输出警告 drop_console: true, //删除全部console语句,能够兼容IE collapse_vars: true, //内嵌已定义但只使用一次的变量 reduce_vars: true, //提取使用屡次但没定义的静态值到变量 }, output: { beautify: false, //最紧凑的输出,不保留空格和制表符 comments: false, //删除全部注释 } }) ] }
const manifest = require('../public/static/dll/vendor.manifest.json'); ... plugins: [ new webpack.DllReferencePlugin({ manifest }), ]
<script src="/static/dll/vendor.js"></script>
end.
demo地址json