解决 react webpack 每次发布新版本后需要用户手动强制刷新,来更新缓存的问题
本节主要说明下使用hash命名的好处,很多时候浏览器为我们访问页面的时候很多资源文件都都是缓存在本地。如果缓存时间没过期不会请求新的资源文件,但有时候如果对某个资源进行了修改,没及时更新就会有问题。因此webpack在打包的时候会为我们生成一个hash值。这个hash值会随源文件或资源的变动而变化,如果源文件不动,资源不动。啥也不动的情况下,多次编译生成的hash是一样。这个不用担心。并不会每次编译都产生不同的hash.
AdeMacBook-Pro-3:webpackdemo a$ npm run dev
> webpackdemo@1.0.0 dev /Users/a/Documents/reactNative/reactstudy/webpackdemo
> webpack-dev-server
ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from /Users/a/Documents/reactNative/reactstudy/webpackdemo/dist
ℹ 「wdm」: Hash: 3657098ad25ae41f7382
Version: webpack 4.29.6
Time: 1397ms
...
从上面中我们可以看到产生的hash 3657098ad25ae41f7382
怎么使用这个hash值呢。在webpack.config.js中在你需要使用hash值来命名输出的名件名时。通过[hash]来读取。
const path = require('path');
const htmlplugin = require('html-webpack-plugin')
module.exports = {
...
output: {
filename: 'bundle.[hash].js',
path: path.resolve(__dirname, 'dist')
},
...
}
这样修改之后,就会带hash值了。
但加了hash值之后。每次改动源码编译后都会产生新的hash文件,那第dist里就会有好多没有用的过时的文件垃圾。每次都手动删除。比较烦。这时可以按装一个clean-webpack-plugin https://www.npmjs.com/package/clean-webpack-plugin
filename 相关的地方都加上 .[hash] 使每次发布依赖的文件都不一样,进而不使用以前旧的缓存文件。
const path = require('path');
const htmlplugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
let pathsToClean = [
'dist/*.*',
'build'
]
let cleanOptions = {
root: __dirname,
verbose: true,
dry: false
}
module.exports = {
...
output: {
filename: 'bundle.[hash].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new CleanWebpackPlugin(pathsToClean, cleanOptions),
new htmlplugin({
title: 'Html 插件 Demo',
template: path.join(__dirname, 'public', 'index.html')
})
],
...
}
到此hash算是完成了基本使用吧。
网友评论