1. Webpack 的主要作用
1. 模块打包
- 将 TypeScript 转换为 JavaScript
2. 减小打包体积的方法
- 代码分割 (Code Splitting)
- // webpack.config.js
- module.exports = {
- optimization: {
- splitChunks: {
- chunks: 'all',
- minSize: 20000,
- minChunks: 1,
- maxAsyncRequests: 30,
- maxInitialRequests: 30,
- cacheGroups: {
- vendors: {
- test: /[\\/]node_modules[\\/]/,
- priority: -10
- },
- default: {
- minChunks: 2,
- priority: -20,
- reuseExistingChunk: true
- }
- }
- }
- }
- }
复制代码- 压缩代码
- // webpack.config.js
- const TerserPlugin = require('terser-webpack-plugin');
- module.exports = {
- optimization: {
- minimize: true,
- minimizer: [new TerserPlugin()],
- }
- }
复制代码
- Tree Shaking(移除未使用的代码)
- // package.json
- {
- "sideEffects": false
- }
- // webpack.config.js
- module.exports = {
- mode: 'production', // 启用 tree shaking
- optimization: {
- usedExports: true
- }
- }
复制代码
- 使用动态导入 // 代码中使用动态导入
- const Component = () => import('./Component.vue')
复制代码
- 压缩图片
- // webpack.config.js
- module.exports = {
- module: {
- rules: [
- {
- test: /\.(png|jpg|gif)$/i,
- use: [
- {
- loader: 'image-webpack-loader',
- options: {
- mozjpeg: {
- progressive: true,
- quality: 65
- }
- }
- }
- ]
- }
- ]
- }
- }
复制代码 6. 使用 gzip 压缩
- // webpack.config.js
- const CompressionPlugin = require('compression-webpack-plugin');
- module.exports = {
- plugins: [
- new CompressionPlugin({
- algorithm: 'gzip',
- test: /\.js$|\.css$|\.html$/,
- threshold: 10240,
- minRatio: 0.8
- })
- ]
- }
复制代码 3. 其他优化建议
- 分析打包巨细
- # 使用 webpack-bundle-analyzer 分析包大小
- npm install --save-dev webpack-bundle-analyzer
复制代码 2. 优化第三方库的引入
- // 按需引入
- import { Button } from 'element-ui' // 而不是 import ElementUI from 'element-ui'
复制代码 3. 配置 externals
- // webpack.config.js
- module.exports = {
- externals: {
- 'vue': 'Vue',
- 'vue-router': 'VueRouter',
- 'vuex': 'Vuex'
- }
- }
复制代码
- 使用 CDN
- <!-- index.html -->
- <script src="https://cdn.jsdelivr.net/npm/vue"></script>
复制代码 4. 现实结果监控
- 使用 webpack-bundle-analyzer 检察打包结果
- // webpack.config.js
- const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
- module.exports = {
- plugins: [
- new BundleAnalyzerPlugin()
- ]
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |