webpack插件篇-build产物上传cdn

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

此举将会有如下效果



  
    
    
    
    
    
    
    
    
    
    页面标题
    
    
    
    
  
  
    

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

你可能感兴趣的:(webpack插件篇-build产物上传cdn)