webpack插件篇-build產(chǎn)物上傳cdn

1、需求背景

為了優(yōu)化代碼下載速度,我們使用cdn的方式,故需要將打包產(chǎn)物上傳至cdn。

注意點

  • 只有生產(chǎn)環(huán)境才上傳cdn,dev和sim環(huán)境無需上傳

2、代碼實現(xiàn)

代碼實現(xiàn)分為2個部分

  • publicpath配置:保證index.html中的靜態(tài)資源的鏈接公共路徑一致,不存在相對路徑
  • 文件上傳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="頁面標(biāo)題" />
    <link rel="apple-touch-icon" href="/logo.png" />
    <link rel="manifest" href="/manifest.json" />
    <title>頁面標(biāo)題</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  rel="stylesheet" />
    <link  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)
      }
    })
  }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容