如果你喜欢这系列的文章,欢迎star
我的项目,源码地址,点击这里
生产环境代码压缩
虽说生产环境只要配置了 mode:"production"
就能实现 js
的代码压缩,但我们不仅要压缩 js
代码,还需要压缩 css
html
文件
可以先打开 bin/css/app.css
文件,会发现,css
文件格式是未压缩的
之前的章节中已经抽取了 css
文件,用到了 mini-css-extract-plugin
官方已经给了我们压缩的办法, 访问链接 https://webpack.js.org/plugins/mini-css-extract-plugin/#src/components/Sidebar/Sidebar.jsx
文章下面 Minimizing For Production
说的就是压缩 css
代码
能够看到,他们还用到了 uglifyjs-webpack-plugin
插件,这个插件在 webpack4.x
以前是用在 plugins
配置里的,在 webpack4.x
新增了 optimization
配置:
optimization.minimize
用于控制压缩的开关,开发环境默认关闭,生产环境默认开启optimization.minimizer
用于配置压缩项及其配置项optimization.splitChunks
用于拆分代码,找到 chunk 中共同依赖的模块,取出来生成单独的 chunkoptimization.runtimeChunk
将 webpack 生成的 runtime 作为独立 chunk ,runtime 包含在模块交互时,模块所需的加载和解析逻辑(manifest)。
对于压缩代码这一块,官方的例子已经足够好,我们基本不用做修改,直接拿来用就可
但是需要注意的是,uglifyjs-webpack-plugin
在这里使用需要配合babel
配置的.babelrc
文件才能对 es6
语法进行压缩,如果未做相关babel
配置,npm run build
会报错
npm i uglifyjs-webpack-plugin optimize-css-assets-webpack-plugin -D
修改 webpack.prod.conf.js
增加如下配置:
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
optimization: {
minimizer: [ // 用于配置 minimizers 和选项
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true // set to true if you want JS source maps
}),
new OptimizeCSSAssetsPlugin({})
]
},
完成已以上操作,执行 npm run build
是不是发现 css
文件已经压缩,这样我们就完成了 css
js
文件的压缩
还剩下 html
文件没有压缩,可以先打开dist/index.html
文件看一下,文件是未压缩的有格式的状态。
在之前的文章中,我们用到了 html-webpack-plugin
插件,在之前打开的链接页面的左侧导航中,就可以找到这个插件,先看一下这个插件的配置
-
title
: 用于生成的 HTML 文件的标题。 -
filename
: 用于生成的 HTML 文件的名称,默认是 index.html。你可以在这里指定子目录(例如:assets/admin.html) -
template
: 模板的路径。 -
inject
: true | ‘head’ | ‘body’ | false 。把所有产出文件注入到给定的 template 或templateContent。当传入 true 或者 ‘body’ 时所有 javascript 资源将被放置在body 元素的底部,‘head’ 则会放在 head 元素内。 -
favicon
: 给定的图标路径,可将其添加到输出 html 中。 -
meta
: 配置 html 文件的 meta 值,可以配置移动端 meta 也可以配置 seo 优化相关 meta -
minify
: {…} | false 。传一个 html-minifier 插件的配置 object 来压缩输出。 -
hash
: true | false。如果是 true ,会给所有包含的 scrip t和 css 添加一个唯一的 webpack 编译 hash 值。这对于缓存清除非常有用。 -
cache
: true | false 。如果传入 true(默认),只有在文件变化时才 发送(emit)文件。 -
showErrors
: true | false 。如果传入 true(默认),错误信息将写入 html 页面。 -
chunks
: 只允许你添加chunks 。(例如:只有单元测试块 ) -
chunksSortMode
: 在 chunk 被插入到 html 之前,你可以控制它们的排序。允许的值 ‘none’ | ‘auto’ | ‘dependency’ | {function} 默认为‘auto’. -
excludeChunks
: 允许你跳过一些 chunks(例如,不要单元测试的 chunk). -
xhtml
: true | false。如果是 true ,会兼容xhtml
文件。
比较常用的是前 5 个,meta
移动端或多页应用可以使用,本文要说的是第 7 个 minify
~
这个插件的详细配置 webpack
中没有详细使用说明,但是在 Configuration
下面已经给出了所有配置项详细的链接,点链接,我们就进到了这个插件在 github
上的源码页面,下面的 Options
列出了这个插件的所有配置项,有需要其他配置的,可以自行查阅,本章所讲是压缩 html
文件,所以我们只关注 mimify
这一项,看这一项的描述,可以知道,它依托的是 html-minifier
的配置项,好吧~ 这层层往下找去吧~
我们再通过点击 html-minifier
进入该插件的页面,直接跳转到了配置项这一块,我们改进之前的 html-webpack-plugin
的配置如下:
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.join(__dirname, './src/index.html'),
minify:{
removeRedundantAttributes:true, // 删除多余的属性
collapseWhitespace:true, // 折叠空白区域
removeAttributeQuotes: true, // 移除属性的引号
removeComments: true, // 移除注释
collapseBooleanAttributes: true // 省略只有 boolean 值的属性值 例如:readonly checked
},
title:'webpack-主页',
favicon:''
}),
执行命令 npm run build
编辑器打开 dist/index.html
文件,代码是不是已经被压缩了呢~
相关文件配置信息更新情况
以下为本文已涉及到的配置文件的当前详细信息
webpack.prod.conf.js
文件现在的配置信息情况:
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
// 入口文件配置项
entry:{
app:[path.resolve(__dirname, 'src/index.js')],
},
// 输出文件配置项
output:{
path:path.resolve(__dirname,"dist"),
filename: 'js/[name].[chunkhash].js',
chunkFilename: 'js/[name].[chunkhash].js',
publicPath:""
},
// 开发工具
devtool: 'cheap-module-source-map',
// webpack4.x 环境配置项
mode:"production",
// 加载器 loader 配置项
module:{
rules:[
{
test: /\.(js|jsx)$/,
use: ['babel-loader?cacheDirectory=true'],
include: path.resolve(__dirname, 'src')
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader'
},{
loader: 'postcss-loader',
options: {
sourceMap: true,
config: {
path: 'postcss.config.js'
}
}
}
]
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
config: {
path: 'postcss.config.js'
}
}
},
{
loader: 'sass-loader',
options: { sourceMap: true }
}
],
exclude: /node_modules/
},
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
importLoaders: 1,
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
config: {
path: 'postcss.config.js'
}
}
},
{
loader: 'less-loader',
options: {
sourceMap: true,
}
}
]
},
{
test: /\.(png|jp?g|gif|svg)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192, // 小于8192字节的图片打包成base 64图片
name:'images/[name].[hash:8].[ext]',
publicPath:''
}
}
]
},
{
// 文件依赖配置项——字体图标
test: /\.(woff|woff2|svg|eot|ttf)$/,
use: [{
loader: 'file-loader',
options: {
limit: 8192,
name: 'fonts/[name].[ext]?[hash:8]',
publicPath:''
},
}],
}, {
// 文件依赖配置项——音频
test: /\.(wav|mp3|ogg)?$/,
use: [{
loader: 'file-loader',
options: {
limit: 8192,
name: 'audios/[name].[ext]?[hash:8]',
publicPath:''
},
}],
}, {
// 文件依赖配置项——视频
test: /\.(ogg|mpeg4|webm)?$/,
use: [{
loader: 'file-loader',
options: {
limit: 8192,
name: 'videos/[name].[ext]?[hash:8]',
publicPath:''
},
}],
}, {
test:/\.html$/,
use:[
{
loader:"html-loader",
options:{
attrs:["img:src","img:data-src"]
}
}
]
}
]
},
// webpack4.x 新增配置项
optimization: {
minimizer: [ // 用于配置 minimizers 和选项
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true // set to true if you want JS source maps
}),
new OptimizeCSSAssetsPlugin({})
]
},
// 插件配置项
plugins: [
new CleanWebpackPlugin(),
new webpack.HashedModuleIdsPlugin(),// 实现持久化缓存
new HtmlWebpackPlugin({
filename: 'index.html',// 输出文件的名称
template: path.resolve(__dirname, 'src/index.html'),// 模板文件的路径
title:'webpack-主页',// 配置生成页面的标题
minify:{
removeRedundantAttributes:true, // 删除多余的属性
collapseWhitespace:true, // 折叠空白区域
removeAttributeQuotes: true, // 移除属性的引号
removeComments: true, // 移除注释
collapseBooleanAttributes: true // 省略只有 boolean 值的属性值 例如:readonly checked
},
favicon:''
}),
new MiniCssExtractPlugin({
filename: "css/[name].[hash].css",
chunkFilename: "css/[name].[hash].css"
})
],
}