Webpack 4 配置
Vue CLI vs Webpack 4 配置对比、常用 Loader 和 Plugin
配置对比
Vue CLI 配置 vs Webpack 4 原生配置
// vue.config.js
module.exports = {
publicPath: '/',
outputDir: 'dist',
assetsDir: 'static',
lintOnSave: true,
devServer: {
port: 8080,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true
}
}
},
configureWebpack: {
// 简单配置
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
}
}
}
// webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: './src/index.tsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.[hash].js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'less-loader'
]
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
alias: {
'@': path.resolve(__dirname, 'src')
}
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html'
})
],
devServer: {
port: 8080,
historyApiFallback: true,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true
}
}
}
}
常用 Loaders
Webpack 4 处理各种文件类型的加载器
| Loader | 用途 | 配置示例 |
|---|---|---|
ts-loader |
处理 TypeScript | test: /\.tsx?$/ |
babel-loader |
ES6+ 转译 | test: /\.jsx?$/ |
css-loader |
处理 CSS | test: /\.css$/ |
less-loader |
处理 Less | test: /\.less$/ |
sass-loader |
处理 Sass/SCSS | test: /\.scss$/ |
style-loader |
注入 CSS 到 DOM | 与 css-loader 配合 |
file-loader |
处理文件 | test: /\.(png|jpg|gif)$/ |
CSS Modules 配置
{
test: /\.module\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: {
localIdentName: '[name]__[local]--[hash:base64:5]'
}
}
}
]
}
常用 Plugins
Webpack 4 插件,扩展构建功能
HtmlWebpackPlugin
自动生成 HTML 文件并注入打包后的资源
MiniCssExtractPlugin
将 CSS 提取到单独的文件
CleanWebpackPlugin
构建前清理输出目录
BundleAnalyzerPlugin
分析打包体积
插件配置示例
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
module.exports = {
plugins: [
// 清理输出目录
new CleanWebpackPlugin(),
// 生成 HTML
new HtmlWebpackPlugin({
template: './public/index.html',
minify: {
collapseWhitespace: true,
removeComments: true
}
}),
// 提取 CSS
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css'
}),
// 分析打包体积(开发时使用)
new BundleAnalyzerPlugin()
]
}
常用命令
Vue CLI 命令 vs Webpack 4 命令
| 功能 | Vue CLI | Webpack 4 |
|---|---|---|
| 启动开发服务器 | npm run serve |
webpack-dev-server |
| 生产构建 | npm run build |
webpack --mode production |
| 查看配置 | vue inspect |
webpack --display-error-details |
| 分析打包 | npm run build -- --report |
webpack --profile --json |
package.json 脚本配置
{
"scripts": {
"start": "webpack-dev-server --mode development --open",
"build": "webpack --mode production",
"build:analyze": "ANALYZE=true webpack --mode production",
"lint": "eslint src/**/*.{ts,tsx}"
}
}