webpack插件篇-build产物上传cdn

2022-11-22  本文已影响0人  叶小七的真命天子

1、需求背景

为了优化代码下载速度,我们使用cdn的方式,故需要将打包产物上传至cdn。

注意点

2、代码实现

代码实现分为2个部分

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)
      }
    })
  }
}

上一篇下一篇

猜你喜欢

热点阅读