Vue CLI 3.x通过配置chainWebpack将favicon图标打包进指定文件夹内
需求:
线上要求将所有前端静态资源部署到cdn上,打包后的dist目录要求项目名称套时间戳,将所有静态资源放时间戳文件夹内,运维上线时,只取时间戳文件夹上线。
方法:
- 创建cdn地址配置文件public-path.js
const publicPath = 'https://cdn.test.com/'
module.exports = publicPath
- 创建静态文件存放目录配置文件subdirectory-path.js
const time = new Date().getTime()
const serveName = 'test'
const subdir = serveName + '/' + time
module.exports = subdir
-
创建vue.config.js文件
由于从vue cli3开始,Vue推荐零配置快速开发,所以将原先的webpack配置都隐藏了,如果需要自定义配置,需要新建vue.config.js来配置。
这个需求我们需要的配置:const subdirectoryPath = require('./config/subdirectory-path') const publicPath = require('./config/public-path') module.exports = { publicPath: process.env.NODE_ENV === 'production' ? publicPath : '/', assetsDir: subdirectoryPath }
-
去除router.js里的base配置
base配置会在我们所有的路由跳转时加上我们配置的publicPath,就像:
这不是我们想要的,所以要删除:base: process.env.BASE_URL //删除这行
-
将favicon图标打包进时间戳文件夹
用 vue cli3 创建的项目,public文件夹内有index.html和favicon.ico作为模板页面,这时favicon图标在index.html的引用路径是:<link rel="icon" href="<%= BASE_URL %>favicon.ico">
由于我们更改了publicPath的配置,所以此时 <%= BASE_URL %> 的值为https://cdn.youximao.com/ ,这样线上favicon的路径是找不到的,因为我们的静态资源都是在 https://cdn.youximao.com/服务名/时间戳/… 下的,所以我们需要将favicon打包进时间戳文件夹。但当前favicon文件存放在public文件夹内,任何放置在 public 文件夹的静态资源都会被简单的复制到dist目录,所以我们需要先将favicon文件打包进时间戳文件夹。这时我们就可以用到 CopyWebpackPlugin 插件,这个插件可以将单个文件或整个目录复制到构建目录。
1. 首先我们在src文件夹下创建static文件夹,用来存放额外的静态资源文件,将favicon图标放进去。
2. 在vue.config.js配置CopyWebpackPlugin
先通过**vue inspect --plugin copy**查看默认的配置为:
new CopyWebpackPlugin([{
from: '/Users/mac/workspace/dashboard/public',
to: '/Users/mac/workspace/dashboard/dist',
toType: 'dir',
ignore: [
'.DS_Store'
]
}])
在chainWebpack配置插件:
chainWebpack: (config) => {
config
.plugin('copy')
.tap(args => {
args[0][0].from = 'static'
args[0][0].to = subdirectoryPath
return args
})
},
然后再通过vue inspect --plugin copy查看配置就会变成:
new CopyWebpackPlugin([{
from: 'static', // 修改这个
to: 'dashboard/1535235430778', // 修改这个
toType: 'dir',
ignore: [
'.DS_Store'
]
}])
这时候打包的时候,favicon就会打包到时间戳文件夹下。
- 最后还需要修改index.html里favicon的路径
需要使用被 html-webpack-plugin 暴露的默认值
在chainWebpack配置html-webpack-plugin的默认值:
chainWebpack: (config) => {
config
.plugin('html')
.tap(args => {
args[0].baseUrl = publicPath
args[0].static = subdirectoryPath
return args
})
},
使用vue inspect --plugin html查看已修改为:
new HtmlWebpackPlugin(
{
templateParameters: function () { /* omitted long function */ },
template: '/Users/mac/workspace/dashboard/public/index.html',
baseUrl: 'https://cdn.youximao.com/',
'static': 'dashboard/1565245103747'
}
)
这样就把index.html里favicon的路径修改为:
<link rel="icon" href="${htmlWebpackPlugin.options.baseUrl}${htmlWebpackPlugin.options.static}/favicon.ico">
OK,收工