webpack系列文章
- webpack由浅入深——(webpack基础配置)
- webpack由浅入深——(webpack优化配置)
- webpack由浅入深——(tapable)
- webpack由浅入深——(webapck简易版)
- webpack由浅入深——(ast、loader和plugin)
webpack的优化分类
- 优化webpack解析编译过程,减少webpack打包的时间,但是不能减少生成资源文件体积
- 优化webpack编译输出的代码,减少生成资源文件体积
优化webpack解析编译过程
resolve参数设置
- extensions:使用require或import引入文件时可以省略后缀
resolve:{
extensions:['.js','.css','.vue']
},
- alias:别名,简化引用路径
resolve:{
extensions:['.js','.css','.vue'],
alias:{
bootstrap:'bootstrap/dist/css/bootstrap.css' //import 'bootstrap'会找对应的路径
}
},
- mainFields:require和import默认通过第三方插件的package.json中main字段中的地址来引用文件,而bootstrap中main字段使用的,可以通过设置来使用备用字段
resolve:{
extensions:['.js','.css','.vue'],
mainFields:['style','main'] //先找style字段再找main
},
- modules:限制引入第三方的范围
resolve:{
extensions:['.js','.css','.vue'],
mainFields:['style','main'],
modules:[path.resolve(__dirname,node_modules),modle] //modle为自己写的插件或组件
},
- mianFiles:范围下的默认优先查找的文件名
resolve:{
extensions:['.js','.css','.vue'],
mainFields:['style','main'],
modules:[path.resolve(__dirname,node_modules),modle],
mianFiles:['index.js','main.js']
},
noParse
对于某些库,例如:lodash和jquery,其中没有使用require和import引用模块,那么库就不需要使用webpack进行解析分析依赖。
module.exports = {
entry:{
index:'./src/index'
},
output: {
filename:'[name].[hash:8].js',
path: path.resolve(__dirname,'dist')
},
module: {
noParse:/jquery|lodash/,
rules:[]
}
}
提供和暴露变量
- webpack.ProvidePlugin:该插件会提供一个全局变量,在文件中不需要使用require和import引入模块,但是不能提供给外界使用。
npm install jquery
const path = require('path');
const webpack =require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry:{
index:'./src/index'
},
output: {
filename:'[name].[hash:8].js',
path: path.resolve(__dirname,'dist')
},
module: {
rules:[
{
test:/\.css$/,
use:[{
loader:MiniCssExtractPlugin.loader,
},'css-loader']
},
{
test:/\.jpg|png/,
use:{
loader:'url-loader',
options:{
limit:8*1024
}
}
},
{
test:/\.html$/,
use:'html-withimg-loader'
},
{ //使用babel-loader
test:/\.js$/,
use:'babel-loader',
exclude:'/node_modules/'
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.ProvidePlugin({
"$":'jquery' //在全局下添加$变量,不需要再次引入
}),
new MiniCssExtractPlugin({
filename:index.css,
}),
new HtmlWebpackPlugin({
template:'./src/index.html',
filename:'index.html',
chunks:['index']
})
],
devServer: {
contentBase:'./dist',
port:'3000',
hot:true
},
resolve:{},
}
//index.js
console.log($) //在全局下添加$变量,不需要再次引入import
//undefine,不会挂载在window上,页面中插入的script标签中获取不到
console.log(window.$)
- expose-loader:挂载在window上暴露给外界使用变量,但是必须先在文件中使用require和import引入一次才可以。
npm install export-loader -D
const path = require('path');
const webpack =require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry:{
index:'./src/index'
},
output: {
filename:'[name].[hash:8].js',
path: path.resolve(__dirname,'dist')
},
module: {
rules:[
{
test:/\.css$/,
use:[{
loader:MiniCssExtractPlugin.loader,
},'css-loader']
},
{
test:/\.jpg|png/,
use:{
loader:'url-loader',
options:{
limit:8*1024
}
}
},
{
test:/\.html$/,
use:'html-withimg-loader'
},
{
test:/\.js$/,
use:'babel-loader',
exclude:'/node_modules/'
},
{
test:/jquery/,
use:{
loader:'expose-loader', //expose-loader暴露$
options:{
$:'jquery'
}
},
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new MiniCssExtractPlugin({
filename:index.css,
}),
new HtmlWebpackPlugin({
template:'./src/index.html',
filename:'index.html',
chunks:['index']
})
],
devServer: {
contentBase:'./dist',
port:'3000',
hot:true
},
resolve:{},
}
//index.js
const $ = require('jquery');
console.log($)
console.log(window.$) //能够挂载在window上
happyPack
webpack支持多个线程进行同时进行打包,以便提高编译打包的速度,但是需要注意,如果项目比较简单,不要采用这种方式,因为线程时需要cpu的花销的,简单的项目而使用多线程编译打包,不仅不能加快打包的速度,反而会降低打包的速度
const path = require('path');
cosnt HappyPack = require('happypack');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname,'dist'),
filename: 'index_bundle.js',
},
module:{
rules:[
{
test: /\.js$/,
loader: 'happypack/loader?id=js',
exclude: /node_modules/,
include: path.resolve(__dirname,'src')
},
{
test: /\.css$/,
loader: 'happypack/loader?id=css',
exclude: /node_modules/,
include: path.resolve(__dirname,'src')
}]
},
plugins: [
new HappyPack({
id: 'js',
threadPool: happyThreadPool,
loaders: [ 'babel-loader' ]
}),
new HappyPack({
id: 'css',
threadPool: happyThreadPool,
loaders: [ 'style-loader', 'css-loader', 'less-loader' ]
})
]
}
Dllplugin
预先编译和打包不会存在变动的文件,在业务代码中直接引入,加快webpack编译打包的速度,但是并不能减少最后生成的代码体积。
import React,{Component} from 'react';
import ReactDoM,{render} from 'react-dom';
这样会存在一个问题,react和reat-dom中的代码基本不会修改,所以用户编写代码修改时,这些代码也会重新编译和打包,这样就很浪费时间,Dllplugin一次编译打包后就会生成一份不变的代码供其他模块引用,节省开发时编译打包的时间。
- 配置webpack.dll.config.js
const path = require('path');
const webpack = require('webpack');
module.exports ={
entry: {
vendor: ['react', 'redux', 'react-router'],
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].dll.js',
library: '[name]_[hash]' //提供全局的变量
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, 'dist', '[name].manifest.json'),
name: '[name]_[hash]',
}),
],
};
- 配置script
"scripts": {
"dev": "webpack-dev-server",
"build": "webpack",
"dll":"webpack --config webpack.dll.config.js"
},
- 配置webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname,'dist'),
filename: 'index_bundle.js',
},
plugins: [
new webpack.DllReferencePlugin({
context: path.join(__dirname),
manifest:path.resolve(__dirname,'dist','vendor.manifest.json')
}),
new HtmlWebpackPlugin(),
new AddAssetHtmlPlugin({
filepath: path.resolve(__dirname,'dist','vendor.manifest.json')
}),
],
};
结构会生成这样的页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Webpack App</title>
</head>
<body>
<script type="text/javascript" src="vendor-manifest.json"></script>
<script type="text/javascript" src="index_bundle.js"></script>
</body>
</html>
抽离公共代码
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
//两个模块都引用了c模块和d模块
pageA:'./src/pageA',
pageB:'./src/pageB',
},
output: {
path: path.resolve(__dirname,'dist'),
filename: '[name].js',
},
optimization:{
splitChunks:{
cacheGroups:{
common:{
chunks:'initial',
minChunks:2, //用两个模块以上同时引用的模块才会抽离出来
minSize:0 //限制大小,太小了没必要抽离
}
}
}
},
plugins:[
new HtmlWebpackPlugin()
]
}
//pageA.js pageB.js
import './pageC'
import './pageD'
//pageC.js
console.log('c')
console.log('d')
生成的页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Webpack App</title>
</head>
<body>
<script type="text/javascript" src="common~pageA~pageB.js"></script>
<script type="text/javascript" src="pageA.js"></script>
<script type="text/javascript" src="pageB.js"></script>
</body>
</html>
优化webpack编译输出的代码
external和cdn引用
将一些公共的文件例如react、react-dom等文件以cdn的方式引入,然后源文件中就不需要打包这些模块,增加一次请求但是减少代码体积。
const path = require('path');
const webpack =require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry:{
index:'./src/index'
},
output: {
filename:'[name].[hash:8].js',
path: path.resolve(__dirname,'dist')
},
module: {
rules:[
{
test:/\.css$/,
use:[{
loader:MiniCssExtractPlugin.loader,
},'css-loader']
},
{
test:/\.jpg|png/,
use:{
loader:'url-loader',
options:{
limit:8*1024
}
}
},
{
test:/\.html$/,
use:'html-withimg-loader'
},
{
test:/\.js$/,
use:'babel-loader',
exclude:'/node_modules/'
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new MiniCssExtractPlugin({
filename:index.css,
}),
new HtmlWebpackPlugin({
template:'./src/index.html',
filename:'index.html',
chunks:['index']
})
],
externals:{
'jquery':'$' //表明jquery是外链CDN引用
}
devServer: {
contentBase:'./dist',
port:'3000',
hot:true
},
resolve:{},
}
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</body>
</html>
IgnorePlugin
IgnorePlugin用于忽略某些特定的模块,让 webpack 不把这些指定的模块打包进去
const path = require('path');
const webpack =require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry:{
index:'./src/index'
},
output: {
filename:'[name].[hash:8].js',
path: path.resolve(__dirname,'dist')
},
module: {},
plugins: [
//moment中的语言包很大,其他语言根本就没有必要打包
//需要的语言单独引入
new webpack.IgnorePlugin(/^\.\/locale/,/moment$/)
],
devServer: {
contentBase:'./dist',
port:'3000',
hot:true
},
resolve:{},
}
import moment from 'moment';
//需要的语言单独引入
require('moment/locale/zh-cn');
console.log(moment);
使用IgnorePlugin前
使用IgnorePlugin后懒加载
webpack内部定义用户异步加载模块的使用方法,用于减少资源文件的体积。
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {HashRouter as Router,Route} from 'react-router-dom';
import Bundle from './Bundle';
let LazyAbout=(props) => (<Bundle {...props} load={()=>import('./About')}/>)
let Home=() => <div>Home</div>
ReactDOM.render(
<Router>
<div>
<Route path="/" component={Home} />
<Route path="/about" component={LazyAbout}/>
</div>
</Router>,document.getElementById('root'));
//Bundle
import React from 'react';
export default class Bundle extends React.Component{
state={Mod: null}
componentWillMount() {
this.props.load().then(mod=>this.setState({Mod: mod.default? mod.default:mod}));
}
render() {
let Mod=this.state.Mod;
return Mod&&<Mod {...this.props}/>;
}
}
//About
import React from 'react';
export default props => <div>About</div>
tree-shaking
tree-shaking会将一些没有用到的代码自动删除掉,这是webpack4内部自带的功能,这里有一个前提就是代码必须采用es6的模块方式import,不然没有办法使用tree-shaking
//a.js
export a = ()=>'a';
export b = ()=>'b';
//index.js
import {a} from './a'
console.log(a());
最后打后的代码会删除掉b
变量提升
webpack会将某些代码进行优化,以更简洁的方式来替代。
//c.js
export default 'kbz'
//index.js
import c from './c'
console.log(c);
//这两行会简化为 var c = 'kbz'
const path = require('path');
const ModuleConcatenationPlugin = require('webpack/lib/optimize/ModuleConcatenationPlugin')
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname,'dist'),
filename: 'index_bundle.js',
},
module:{
},
plugins: [
new ModuleConcatenationPlugin()
]
}
结语:
以上就是一些关于webpack优化的一些手段。