在中了解了webpack v4的特性,现在将知识用于实践,对之前写的一个react脚手架进行打包性能的优化。
优化类目
- 样式分离
- 第三方资源分离
- 区分开发环境
- 热更新
- 提取公共代码
1. CSS分离
webpack.config.js
将css、less、sass文件单独从打包文件中分离
在webpack.config.js中单独添加规则,
- test:匹配处理文件的扩展名的正则表达式
- include/exclude手动指定必须处理的文件夹或屏蔽不需要处理的文件夹
然后运行webpack命令时报错
compilation.mainTemplate.applyPluginsWaterfall is not a function
Use Chunks.groupsIterable and filter by instanceof Entrypoint instead
研究得出结论:webpack升级到v4然而响应的插件没有升级的原故。
解决方法:安装指定版本的依赖
resolve
指定extension之后可以不用在require或是import的时候加文件扩展名,会依次尝试添加扩展名进行匹配
监听文件修改
webpack模式下使用,webpack-dev-server模式不用,可以将watch改为false
提取公共代码
分离react react-dom ant公共代码
方法一:externals
在页面上引入第三方资源库,然后使用externals防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies)。
分离成功!上代码
webpack.base.js
filename: 'css.css',allChunks: true
});
let sassExtract = new ExtractTextWebpackPlugin('sass.css')
let lessExtract = new ExtractTextWebpackPlugin('less.css')
module.exports = {
entry:'./src/index.js',output: {
path: path.resolve(dirname,'./dist'),filename: 'bundle.[hash:8].js',publicPath: ''
},resolve: {
//引入模块的时候,可以不用扩展名
extensions: [".js",alias: {//别名
"bootstrap": "bootstrap/dist/css/bootstrap.css"
},modules: [path.resolve(dirname,'node_modules')]
},/ externals: {
'react': 'React',// 提出ant design的公共资源
//'antd': 'antd',},/
devtool: 'source-map',devServer: {
contentBase:path.resolve(dirname,'dist'),publicPath: '/',port: 8080,hot:true,compress:true,historyApiFallback: true,inline: true
},watch: false,//只有在开启监听模式时,watchOptions才有意义
watchOptions: {
ignored: /node_modules/,//监听到变化发生后等300ms再去执行动作,防止文件更新太快导致编译频率太高
poll: 1000 //通过不停的询问文件是否改变来判断文件是否发生变化,默认每秒询问1000次
},optimization: {
splitChunks: {
cacheGroups: {
commons: {
chunks: "initial",enforce: true
}
}
}
},module: {
rules:[
{
test: /.js$/,use: {
loader:'babel-loader',options: {
presets: ['env','es2015','react'],}
},exclude:/node_modules/
},{
test: /.css$/,use: cssExtract.extract({
fallback: "style-loader",use: sassExtract.extract({
fallback: "style-loader",loader: lessExtract.extract({
use: ["css-loader?minimize",{
test: /.(html|htm)/,use: 'html-withimg-loader'
},{
test: /.(png|jpg|gif|svg|bmp|eot|woff|woff2|ttf)/,use: {
loader:'url-loader',options:{
limit: 5 * 1024,//指定拷贝文件的输出目录
outputPath: 'images/'
}
}
}
]
},plugins: [
//定义环境变量
new webpack.DefinePlugin({
development__: JSON.stringify(process.env.NODE_ENV)
}),new CleanWebpackPlugin(['dist']),cssExtract,lessExtract,sassExtract,new HtmlWebpackPlugin({
title: 'React Biolerplate by YuanYuan',template: './src/index.html',filename: index.html
,hash: true
}),new webpack.DllReferencePlugin({
manifest: path.join(dirname,'vendor','react.manifest.json')
}),new CopyWebpackPlugin([{
from: path.join(dirname,'vendor'),//静态资源目录源地址
to:'./vendor' //目标地址,相对于output的path目录
}]),/* new webpack.optimize.CommonsChunkPlugin({
name: 'common' // 指定公共 bundle 的名称。
- })*/
new webpack.HotModuleReplacementPlugin(),// 热替换插件
new webpack.NamedModulesPlugin() // 执行热替换时打印模块名字
]
};
webpack.config.js
//console.log(process.env.NODE_ENV )
if (process.env.NODE_ENV == 'development') {
other = require('./webpack.dev.config');
} else {
other = require('./webpack.prod.config');
}
//console.log(merge(base,other));
module.exports = merge(base,other);
webpack.prod.config.js
const path = require('path');
const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
output: {
filename: 'bundle.min.js',plugins: [
new UglifyJSPlugin({sourceMap: true})
]
}
打包速度优化,打包文件细化,改造成功~