说明
玩转webpack
课程学习笔记。
什么是文件指纹
打包后输出的文件名的后缀。
文件指纹如何生成
-
Hash
:和整个项目的构建相关,只要项目文件有修改,整个项目构建的hash
值就会更改 -
Chunkhash
:和webpack
打包的chunk
有关,不同的entry
会生成不不同的chunkhash
值 -
Contenthash
:根据文件内容来定义hash
,文件内容不变,则contenthash
不变
JS 的文件指纹设置
设置 output
的 filename
,使用 [chunkhash]
。
注意:mode: 'production'
module.exports = {
entry: {
index: './src/index.js',
search: './src/search.js'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name]_[chunkhash].js'
},
mode: 'production',
};
图片和字体的文件指纹设置
设置 file-loader
的 name
,使用 [hash]
。
占位符名称 | 含义 |
[ext] | 资源后缀名 |
[name] | 文件名称 |
[path] | 文件相对路径 |
[folder] | 文件所在的文件夹 |
[contenthash] | 文件的内容hash,默认是md5生成 |
[hash] | 文件内容的hash,默认是md5生成 |
[emoji] | 一个随机的指代文件内容的emoji |
module.exports = {
entry: {
index: './src/index.js',
search: './src/search.js'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name]_[chunkhash].js'
},
mode: 'production',
module: {
rules: [
{
test: /.(png|jpg|gif|jpeg)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name]_[hash:8].[ext]'
}
}
]
},
{
test: /.(woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name]_[hash:8].[ext]'
}
}
]
},
]
},
};
有无文件指纹打包对比
下面是js、图片、字体的打包对比,css需要另外插件处理
没有文件指纹:
有文件指纹:
CSS 的文件指纹设置
上面的对比没有发现有css文件出现,因为style-loader
是将css插入header里。
这里需要安装插件npm i mini-css-extract-plugin -D
mini-css-extract-plugin
是生成单独的css文件,但跟style-loader
有一定的冲突。
设置 MiniCssExtractPlugin
的 filename
, 使用 [contenthash]
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: {
index: './src/index.js',
search: './src/search.js'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name]_[chunkhash].js'
},
mode: 'production',
module: {
rules: [
{
test: /.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /.less$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'less-loader'
]
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name]_[contenthash:8].css'
})
]
};