1.Library打包
针对于写库的打包。
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path=require('path')
module.exports={
mode:'production',
entry:'./src/index.js',
externals:{//防止重复打包loadsh。
lodash:{
root:'_',//存在-》通过script标签全局引入,需要注入一个_的全局变量
commonjs:'lodash'//针对于通过这种方式引入的
}
},
output:{
path:path.resolve(__dirname,'dist'),
filename:'library.js',
libraryTarget:'umd',//通用引入语法 cmd,es6等。如果等于this=》挂载到this上。如果等于windows=》挂载到windows上
library:'library'//全局变量。script标签引入。
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin()
]
}
2.PWA打包配置
官网配置
PWA:增强用户体验,让网页可以在本地进行使用。主要运用到webpack里面的一个插件。workBox-webpack-plugin。
3.typeScript配置
官网配置
1.添加tsconfig.json
2.添加对应的ts-loader
4.使用WebpackDevServer实现请求转发
//使用
axios.get('/react/api/header.json').then((res)=>{
console.log(res)
})
devServer: {
contentBase: path.join(__dirname, "dist"),
hot: true,
hotOnly: true,
proxy: {
'/react/api': {
target: 'https://www.xxxx.com',
secure: false,//https进行转发需要配置的
pathRewrite: {
'header.json': 'demo.json'//替换结尾地址
},
bypass: function (req, res, proxyOptions) {//拦截
if (req.headers.accept.indexOf('html') !== -1) {
console.log('Skipping proxy for browser request.');
return '/index.html';
}
},
changeOrigin:true,//主机头的起源保持默认进行代理
headers:{//修改请求头
host:'www.dell-lee.com',
cookie:'safsfa'
}
}
}
},
5.WebpackDevserver解决单页面路由问题。
官网地址
应用场景:主要是针对于对js里面产生的页面进行分路由访问。因为单页面正常只有一个对应的url。
devServer: {
//historyApiFallback: true,//对应页面转换成js路由。
historyApiFallback:{
rewrite:[{
from:/abc.html/,
to:'/index.html'//这部分也可以用一个方法类处理
}]
}
}
6.resolve的使用。
resolve: {
extensions: ['.js', '.jsx'], // 引入后缀,尽量只写关于js的文件,不要写css,jpg之内的。
mainFiles: ['index', 'child'], // 默认去找index/child文件
alias: {
'@img': path.resolve(__dirname, '../img'), // @img写一个别名,
},
},
7.webpack打包加速。
1.升级相关版本(Node,Npm,Yarn)
2.在尽可能少的模块上应用Loader
3.Plugin尽可能的精简,同时尽量使用官方的(速度有保障)。
4.resolve参数合理配置
5.使用DllPlugin
(1)创建webpack.dll.js文件。用来提前打包三方包,和生成映射文件。
const path = require('path');// 引入node的一个包
const webpack = require('webpack');
module.exports = {
entry: {
vendors: ['lodash', 'jquery'],
react: ['react', 'react-dom'],
},
output: {
filename: '[name].dll.js',
path: path.resolve(__dirname, './dll'),
library: '[name]',
},
plugins: [
new webpack.DllPlugin({ // 进行映射
name: '[name]',
path: path.resolve(__dirname, './dll/[name].manifest.json'),
}),
],
};
(2)package.json中配置,并运行npm run build:dll。生成打包后的文件dll文件和映射文件。
"scripts": {
"build:dll": "webpack --config webpack.dll.js"
},
(3)在webpack.common.js文件中动态增加配置plugins。
const plugins=[
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'src/index.html',
}),
new webpack.ProvidePlugin({
$: 'jquery'
})
]
const files=fs.readdirSync(path.resolve(__dirname,'./dll'))
files.forEach(file=>{
if(/.*\.dll.js$/.test(file)){
plugins.push(
new AddAssetHtmlWebpackPlugin({//添加js引入
filepath:path.resolve(__dirname,'./dll',file)
})
)
}
if(/.*\.manifest.json$/.test(file)){
plugins.push(
new webpack.DllReferencePlugin({//使用映射
manifest:path.resolve(__dirname,'./dll',file)
})
)
}
})
6.控制包文件大小
主要就是进行代码分割。
optimization: {
usedExports: true,
splitChunks: {
chunks: 'all', // 有效值为all,async和initial。async/initial只对异步/同步代码进行分割
minSize: 20000, // 大于20000才做代码分割
minRemainingSize: 0,
maxSize: 50000, // 大于50000做二次代码分割(在可以的情况下 )
minChunks: 1, // 至少使用了一次才做分割
maxAsyncRequests: 30, // 最大同时加载模块30个
maxInitialRequests: 30, // 首页最多加载模块30个
automaticNameDelimiter: '~', // 文件名链接默认符号
enforceSizeThreshold: 50000, // 强制执行拆分的大小最大50000
cacheGroups: { // 缓存模块组,等待所有模块判断完毕后,再生成文件。
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10, // 权重。判断文件应该打包到那个js文件中。
name: 'vandors',
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true, // 忽略掉已经打包过的js
},
},
},
},
7.thread-loader,parallel-webpack,happypack多进程打包
合理的运用插件
thread-loader:多进程打包
parallel-webpack:多页面打包
8.合理的运用sourceMap
根据不同的环境进行不同的配置
9.结合stats分析打包结果
针对于某个模块打包速度进行优化
使用webpack-bundle-analyzer
10.开发环境内存编译webpack-dev-server
11.开发环境无用插件剔除
8.多页面打包配置
const comConfig = {
entry: {
main: './src/home.js',//入口文件
list: './src/list.js',
},
}
const plugins = [
new HtmlWebpackPlugin({
template: 'src/index.html',//页面模板
filename: 'index.html',//生成html
chunks: ['vandors', 'list'],//引入js
}),
new HtmlWebpackPlugin({
template: 'src/index.html',
filename: 'list.html',
chunks: ['vandors', 'main'],
})
]