2020 年前后,很多团队正好在做一件事:把 jQuery 时代的多页站点,迁到以 Vue/React 为代表的单页应用。迁过去第一道坎不是框架 API,而是构建。这篇文章记录一套从零手写的 Webpack 4 配置,以及当时踩过的坑。
目录结构约定
1 2 3 4 5 6 7 8 9 10 11 12
| project ├── build │ ├── webpack.base.js │ ├── webpack.dev.js │ └── webpack.prod.js ├── public │ └── index.html ├── src │ ├── main.js │ ├── App.vue │ └── assets └── package.json
|
配置拆三层:基础配置、开发配置、生产配置。基础配置只放”两边都一样的部分”,环境差异全部用 webpack-merge 合并,避免出现三份互相抄来抄去的文件。
基础配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| const path = require('path') const VueLoaderPlugin = require('vue-loader/lib/plugin') const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = { entry: path.resolve(__dirname, '../src/main.js'), output: { path: path.resolve(__dirname, '../dist'), filename: 'js/[name].[hash:8].js', publicPath: '/' }, resolve: { extensions: ['.js', '.vue', '.json'], alias: { '@': path.resolve(__dirname, '../src') } }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader' }, { test: /\.js$/, exclude: /node_modules/, use: ['babel-loader'] }, { test: /\.(png|jpe?g|gif|svg)$/i, use: [ { loader: 'url-loader', options: { limit: 8192, name: 'img/[name].[hash:8].[ext]' } } ] } ] }, plugins: [ new VueLoaderPlugin(), new HtmlWebpackPlugin({ template: path.resolve(__dirname, '../public/index.html') }) ] }
|
babel-loader 在这里很关键:当时主流浏览器还要兼容到 IE11,babel.config.js 里必须配上 @babel/preset-env 和 core-js@3,否则打包出来在旧浏览器上直接白屏。
1 2 3 4 5 6 7 8 9 10
| module.exports = { presets: [ ['@babel/preset-env', { useBuiltIns: 'usage', corejs: 3, targets: '> 0.5%, not dead, ie >= 11' }] ] }
|
开发配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const merge = require('webpack-merge') const base = require('./webpack.base') const path = require('path')
module.exports = merge(base, { mode: 'development', devtool: 'eval-cheap-module-source-map', devServer: { contentBase: path.resolve(__dirname, '../dist'), port: 8080, hot: true, open: true, proxy: { '/api': { target: 'http://127.0.0.1:7001', changeOrigin: true } } } })
|
开发环境一定要开 source-map,而且选 eval-cheap-module-source-map,它比 source-map 快得多,报错信息也够定位到具体行。生产环境用 source-map 但不内联,方便线上排错。
生产配置与拆包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| const merge = require('webpack-merge') const base = require('./webpack.base') const CleanWebpackPlugin = require('clean-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const TerserPlugin = require('terser-webpack-plugin')
module.exports = merge(base, { mode: 'production', devtool: 'source-map', module: { rules: [ { test: /\.(css|styl|stylus)$/, use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'stylus-loader'] } ] }, optimization: { minimize: true, minimizer: [ new TerserPlugin({ cache: true, parallel: true, terserOptions: { compress: { drop_console: true } } }) ], splitChunks: { chunks: 'all', cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendor', priority: 10 }, common: { minChunks: 2, minSize: 30000, name: 'common', priority: 5 } } }, runtimeChunk: 'single' }, plugins: [ new CleanWebpackPlugin(), new MiniCssExtractPlugin({ filename: 'css/[name].[contenthash:8].css' }) ] })
|
runtimeChunk: 'single' 一定要加,否则每次发版 manifest 变化会把业务代码的 hash 全带变,浏览器缓存全部失效。
踩过的坑
1. hash / chunkhash / contenthash 用混
hash 是项目级,任何文件改动都会让所有文件名变;chunkhash 是按入口模块算的;contenthash 是按内容算的,最适合 CSS 和图片。JS 用 chunkhash,CSS 用 contenthash,别一刀切。
2. css-loader 的 importLoaders 不写
css-loader 处理到 @import 引入的样式时,默认不会再走后面的 postcss-loader,导致自动补前缀失效。正确写法:
1
| { loader: 'css-loader', options: { importLoaders: 2 } }
|
3. 生产模式默认压缩
Webpack 4 的 mode: 'production' 自带 minimize,很多人自己再加一个 UglifyJsPlugin,结果构建时间翻倍。要么用内置的,要么显式关掉内置再自定义,别两边都开。
4. devtool 泄漏源码
devtool: 'source-map' 会生成独立 .map 文件并部署到线上,源码直接可读。要么在 Nginx 层禁止访问 *.map,要么改用 hidden-source-map 再单独上传到监控平台。
一点感受
这套配置在当年是很典型的写法,它的复杂度主要来自”浏览器兼容 + 多环境 + 缓存策略”三件事。后来构建工具方向变成两个:一个是把配置收敛成预设,另一个是把打包器本身换成更快的语言实现。这份配置在当时的价值是——你至少知道那些一键生成的脚手架到底替你做了什么。