Ai
0 Star 0 Fork 0

嗷大张/webpack5-study

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
webpack.config.js 9.03 KB
一键复制 编辑 原始数据 按行查看 历史
aodazhang 提交于 2023-01-05 14:49 +08:00 . 代码更新
// 一.nodejs 模块
const path = require('path')
// 二.webpack 插件
const { DefinePlugin } = require('webpack')
const { merge } = require('webpack-merge')
const { CleanWebpackPlugin } = require('clean-webpack-plugin') // 清除目录
const HtmlWebpackPlugin = require('html-webpack-plugin') // 根据模板生成 html
const MiniCssExtractPlugin = require('mini-css-extract-plugin') // 提取 css
const TerserWebpackPlugin = require('terser-webpack-plugin') // 压缩 js
const { VueLoaderPlugin } = require('vue-loader') // vue sfc 文件识别
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') // bundle 包分析工具
const CompressionWebpackPlugin = require('compression-webpack-plugin') // 对文件执行压缩
// 三.全局变量
// 生成文件名 hash 规则
const hashRule = '[name]_[contenthash:8]'
// 定义输出的目录
const outputPath = path.resolve(__dirname, 'dist')
// css 公共 loader
const cssLoader = [
{
loader: 'css-loader',
options: {
// css 中通过 @import 引入的文件,也要先执行 sass-loader + postcss-loader
importLoaders: 2
}
},
'postcss-loader',
'sass-loader'
]
// html-webpack-plugin 公共配置
const htmlWebpackPluginOptions = {
template: 'public/index.html', // html 模板位置
favicon: 'public/favicon.ico', // html favicon 位置
filename: 'index.html', // html 生成模板名
chunks: ['main'], // 匹配 entry 的key
title: 'p1.cdn', // html 标题
meta: {
viewport:
'width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no', // html 自适应移动端
description: 'webpack5从不会到入门' // html 描述
},
minify: {
removeComments: true, // html 删除注释
collapseWhitespace: true // html 删除空白符与换行符
}
}
// cdn 配置参数
const cdn = {
externals: {
vue: 'Vue', // 忽略 import 引入第三方库,例如通过 cdn 引入 vue3
'vue-router': 'VueRouter',
vuex: 'Vuex'
},
// html-webpack-plugin 注入 js 脚本,注意需要与 externals 一一对应
js: [
'https://cdn.bootcdn.net/ajax/libs/vue/3.2.45/vue.runtime.global.prod.min.js',
'https://cdn.bootcdn.net/ajax/libs/vue-router/4.1.6/vue-router.global.prod.min.js',
'https://cdn.bootcdn.net/ajax/libs/vuex/4.1.0/vuex.global.prod.min.js'
],
// html-webpack-plugin 注入 css 样式
css: []
}
// 四.公共配置
const commonConfig = {
// 单入口 -> 单输出
entry: {
// 更换为 main.js
main: './src/main.js'
},
output: {
filename: `js/${hashRule}.js`,
// 指定输出的目录
path: outputPath
},
// externals: cdn.externals,
resolve: {
// 路径别名:js -> '@/'、css -> '~@/'
alias: {
'@': path.resolve(__dirname, 'src')
},
// 默认扩展名:.js 必须存在,否则 node_modules 中的文件无法解析
extensions: ['.js', '.vue'] // 加入 vue sfc 扩展名
},
plugins: [
new DefinePlugin({
__VUE_OPTIONS_API__: true, // vue3 开启 options api
__VUE_PROD_DEVTOOLS__: false // vue3 在生产环境中禁用 devtools 支持
}),
new CleanWebpackPlugin({
// 在每次打包前调用:删除输出的目录
cleanOnceBeforeBuildPatterns: [outputPath]
}),
new VueLoaderPlugin() // 配置 vue-loader 内置插件
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/, // 排除 node_modules 中引入的 js 文件
use: ['babel-loader'] // 第三方 loader 通过 use 调用
},
// 识别 vue 文件
{
test: /\.vue$/,
use: ['vue-loader']
},
// 图片 > 100kb 复制到输出目录并将其 url 内联到打包输出的 js 中
// 图片 < 100kb 作为 dataURI 内联到打包输出的 js 中
{
test: /\.(jpg|jpeg|png|gif|bmp|webp|svg|hdr)$/,
type: 'asset',
generator: {
filename: `image/${hashRule}[ext]` // [ext] 代表输出文件原本的扩展名
},
parser: {
dataUrlCondition: {
maxSize: 100 * 1024 // 临界值设定为 100kb
}
}
},
// 字体:复制到输出目录并将其 url 内联到打包输出的 js 中
{
test: /\.(eot|ttf|woff|woff2|fnt)$/,
type: 'asset/resource',
generator: {
filename: `font/${hashRule}[ext]`
}
},
// 音视频:复制到输出目录并将其 url 内联到打包输出的 js 中
{
test: /\.(mp3|mp4|wav)$/,
type: 'asset/resource',
generator: {
filename: `media/${hashRule}[ext]`
}
},
// json、xml:复制到输出目录并将其 url 内联到打包输出的 js 中
{
test: /\.(json|xml)$/,
type: 'asset/resource',
generator: {
filename: `file/${hashRule}[ext]`
}
},
// 着色器语言:将文件作为字符串内联到打包输出的 js 中
{ test: /\.glsl$/, type: 'asset/source' }
]
},
optimization: {
usedExports: true, // 开启 tree shaking
splitChunks: {
chunks: 'all', // 对同步 + 异步引入的 js 开启 code splitting
cacheGroups: {
// vendors 组规则:对 node_modules 引入的 js 文件执行
vendor: {
test: /node_modules/,
name: 'node_modules', // 生成文件名
priority: 1, // 拆分权重:优先级1
minSize: 0 * 1024, // 拆分最小体积(进行拆分 js 文件的最小体积):>=0kb拆分
minChunks: 1 // 拆分最小复用(进行拆分 js 文件的最少 import 次数):>=1次拆分
},
// common 组规则:对所有 js 文件执行
common: {
name: 'common',
priority: 0, // 优先级0
minSize: 0 * 1024, // >=0kb拆分
minChunks: 2 // >=2次拆分
}
}
}
}
}
// 五.开发环境配置
const devConfig = {
mode: 'development',
// 精确到行生成 source map
devtool: 'eval-cheap-module-source-map',
cache: {
type: 'filesystem' // webpack 使用磁盘缓存
},
output: {
publicPath: '/' // 静态资源的公共路径需要设定为当前项目根路径
},
devServer: {
static: {
directory: outputPath // 静态文件目录
},
port: 3000, // 端口号
historyApiFallback: true, // 支持单页应用 history 路由 fallback
open: false, // 禁止自动打开浏览器
hot: true, // 开启热模块重载功能 hmr
compress: true, // 开启 gzip 压缩
client: {
overlay: true, // 在浏览器端显示编译错误
progress: false // 在浏览器端打印编译进度
}
},
plugins: [
new HtmlWebpackPlugin({
...htmlWebpackPluginOptions,
// 开发环境通过 node_modules 引入第三方库
js: [],
css: []
})
],
module: {
rules: [
{
test: /\.(css|scss)$/,
// loader 的执行顺序是从下到上,从右到左
use: ['style-loader', ...cssLoader]
}
]
}
}
// 六.生产环境配置
const prodConfig = {
mode: 'production',
// 关闭 source map
devtool: false,
// 关闭缓存
cache: false,
output: {
publicPath: './'
},
externals: cdn.externals, // 忽略打包的第三方库
plugins: [
new HtmlWebpackPlugin({
...htmlWebpackPluginOptions,
// 生产环境通过 cdn 引入第三方库
js: cdn.js,
css: cdn.css
}),
new MiniCssExtractPlugin({
// 抽离 css 文件名
filename: `css/${hashRule}.css`,
// 抽离 css chunk 文件名
chunkFilename: `css/${hashRule}.chunk.css`
}),
new BundleAnalyzerPlugin({
openAnalyzer: false, // 是否启动本地服务
analyzerMode: 'static', // 只输出静态 html 文件
reportFilename: 'analyzer.html' // 分析文件名称
}),
new CompressionWebpackPlugin({
test: /\.(html|css|js|eot|ttf|woff|woff2|fnt|jpg|jpeg|png|gif|bmp|webp|svg|hdr|mp3|mp4|wav|json|xml)$/, // 匹配文件类型
algorithm: 'gzip', // 压缩算法
threshold: 0 * 1024, // gzip压缩大小阈值(kb):文件大小 >0kb 执行压缩
minRatio: 1.1, // gzip压缩比率阈值(%):文件压缩阈值 <=1 执行压缩
deleteOriginalAssets: false, // 不删除原始文件
filename: '[path][base].gz' // gizp 生成文件名
})
],
module: {
rules: [
{
test: /\.(css|scss)$/,
// loader 的执行顺序是从下到上,从右到左
use: [
MiniCssExtractPlugin.loader, // mini-css-extract-plugin 自带的 loader
...cssLoader
]
}
]
},
optimization: {
minimizer: [
new TerserWebpackPlugin({
parallel: true, // 开启多进程压缩 js
terserOptions: {
compress: {
drop_console: true, // 删除 console
drop_debugger: true // 删除 debugger
}
}
}),
'...' // 其余保持默认值
]
}
}
// 通过环境变量判断合并开发环境还是生产环境配置
module.exports = merge(
commonConfig,
process.env.NODE_ENV == 'development' ? devConfig : prodConfig
)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/aodazhang/webpack5-study.git
git@gitee.com:aodazhang/webpack5-study.git
aodazhang
webpack5-study
webpack5-study
master

搜索帮助