theme: fancy
highlight: a11y-light
Webpack 能够根据模块之间的依赖关系进行打包,实现多个模块的合并和优化,生成优化后的静态资源,支持两种模块导入语法
- html-webpack-plugin 还可以将打包后的 JS、CSS 等静态资源自动注入到 HTML 文件中,不必手动更新引用路径
- 图片小于nkb打包为base64格式,注意只有通过es模块引入才会打包,使用绝对路径不会被打包成base64格式
- 在webpack设置路径别名例如@对应src
- 跨域
"proxy": {
"/api": {
"target": "http://localhost:3001"
},
"/github": {
"target": "https://api.github.com",
"pathRewrite": {
"^/github": "" },
"changeOrigin": true
}
}
//根据前缀转发到不同的地址,注意前缀可能在接口中不存在,就要替换成空,如果地址就有前缀就不需要替换
- 对应第三方包例如antd react,代码基本不会变,我们把这些代码拆分打包,使用splitChunks
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
antd: {
test: /[\/]node_modules[\/](antd)[\/]/,
name: 'antd',
priority: -10
},
reactDOM: {
test: /[\/]node_modules[\/](react-dom)[\/]/,
name: 'react-dom',
priority: -10
},
vendor: {
test: /[\/]node_modules[\/](react|react-dom|antd)[\/]/,
name: "vendors",
chunks: "all",
priority: -10
}//其他第三方统一打包
}
}
}
- 当然在生产环境下我们才需要使用splitChunks或其他插件,我们额外新建一个webpack.prod.config.js文件,使用merge
//webpack.prod.config.js
const webpack = require('webpack');
module.exports =
{
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
antd: {
test: /[\/]node_modules[\/](antd)[\/]/,
name: 'antd',
priority: -10
},
reactDOM: {
test: /[\/]node_modules[\/](react-dom)[\/]/,
name: 'react-dom',
priority: -10
},
vendor: {
test: /[\/]node_modules[\/](react|react-dom|antd)[\/]/,
name: "vendors",
chunks: "all",
priority: -10
}
}
}
}
};
//webpack.config.js
const path = require('path');
const webpack = require('webpack');
const {
merge } = require('webpack-merge');
const defaultConfig = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
],
},
};
if (process.env.NODE_ENV === 'production') {
const prodConfig = require('./webpack.prod.config');
module.exports = merge(defaultConfig, prodConfig);
} else {
module.exports = defaultConfig;
}