Vue CLI: 给 index.html 引入的静态资源 env.js 添加版本号
Vue CLI: 给 index.html 引入的静态资源 env.js 添加版本号
本文介绍如何使用 Vue CLI 为 index.html 引入的静态资源 env.js 添加版本号,以实现缓存控制和资源版本管理。
步骤
- 在
vue.config.js文件中添加如下配置:
module.exports = {
chainWebpack: config => {
config.plugin('html').tap(args => {
args[0].minify = false
args[0].template = './public/index.html'
args[0].filename = 'index.html'
args[0].hash = true // 添加 hash
args[0].env = process.env // 传入环境变量
return args
})
}
}
- 在
index.html文件中添加 script 标签,引入 env.js:
<script src='<%= BASE_URL %>env.js?v=<%= htmlWebpackPlugin.options.hash %>'></script>
其中,<%= BASE_URL %> 是 vue-cli 自动生成的变量,表示应用根路径,<%= htmlWebpackPlugin.options.hash %> 是 vue-cli 自动生成的变量,表示当前构建的 hash 值。
- 执行
npm run build命令,即可在打包后的index.html文件中看到带有 hash 值的env.js。
注意
如果在 index.html 中使用了 <%= BASE_URL %> 变量,需要在 vue.config.js 中添加 publicPath: process.env.NODE_ENV === 'production' ? '/your-project-name/' : '/' 配置,将应用根路径设置为实际的项目名称。
原文地址: https://www.cveoy.top/t/topic/noev 著作权归作者所有。请勿转载和采集!