1、需求背景
为了优化代码下载速度,我们使用cdn的方式,故需要将打包产物上传至cdn。
注意点
- 只有生产环境才上传cdn,dev和sim环境无需上传
2、代码实现
代码实现分为2个部分
- publicpath配置:保证index.html中的静态资源的链接公共路径一致,不存在相对路径
- 文件上传cdn
2.1、配置publicPath
webpack.config.js
const publicPath = IS_PROD ? `https://xxx.cdn.com/${projectName}/${new Date().getTime()}` : '/'
module.exports = {
output: {
publicPath,
}
}
此举将会有如下效果
<!DOCTYPE html>
<html lang="zh" translate="no">
<head>
<meta charset="utf-8" />
<meta name="google" content="notranslate" />
<link rel="icon" href="/favicon.ico" />
<link rel="shortcut icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="页面标题" />
<link rel="apple-touch-icon" href="/logo.png" />
<link rel="manifest" href="/manifest.json" />
<title>页面标题</title>
<script defer="defer" src="https://xxx.cdn.com/projectName/1669101057514/static/js/vendor.e4339d81.js"></script>
<script defer="defer" src="https://xxx.cdn.com/projectName/1669101057514/static/js/main.d208e712.js"></script>
<link href="https://xxx.cdn.com/projectName/1669101057514/static/css/vendor.563fce19.css" rel="stylesheet" />
<link href="https://xxx.cdn.com/projectName/1669101057514/static/css/main.87aa0d4c.css" rel="stylesheet" />
</head>
<body>
<div id="datacenter"></div>
</body>
</html>
2.2、配置webpack插件-上传cdn
const publicPath = IS_PROD ? `https://xxx.cdn.com/${projectName}/${new Date().getFullYear()}` : '/'
module.exports = {
output: {
publicPath,
},
plugins: [
IS_PORD && new UploadCDNWebpackPlugin({publicPath, cdnConfig})
]
}
2.3、编写webpack插件
const fs = require('fs')
const path = require('path')
const globby = require('globby')
const slash = require('slash')
const UploadServer = require('xxxx')
module.exports = class UploadPlugin {
constructor(options) {
this.config = options
}
apply(compiler) {
compiler.hooks.afterEmit.tapPromise('MyPlugin', async compilation => {
const outputPath = path.resolve(slash(compiler.options.output.path))
const files = await globby(`${outputPath}/**`)
if (files.length) {
return this.upload(files, true, outputPath)
} else {
return Promise.resolve()
}
})
}
upload(files, outputPath) {
const uploadServer = new UploadServer(this.config.cdnConfig)
return new Promise(async (resolve, reject) => {
try {
for (const filePath of files) {
await uploadServer(filePath, this.config.publicPath)
console.log(`${filePath} upload success`);
}
} catch (error) {
console.log(`上传cdn失败: ${error}`);
reject(error)
}
})
}
}
网友评论