Vite开发Vue项目时,打包后将图片替换成CDN链接

2023/3/2 ViteVue

在使用 Vite 打包 Vue 项目时,可以使用 Vite 的构建钩子 build:before 来实现将图片引用地址修改为 CDN 地址的功能。
在 beforeWrite.writeBundle 函数中,使用 glob 包获取构建后的文件列表,遍历文件列表,查找并替换所有引用的图片路径。

import glob from 'glob'
import fs from 'fs'

export default {
  // ...
  build: {
    // ...
    beforeWrite: {
      writeBundle: async () => {
        // 定义 CDN 地址
        const cdnBaseUrl = 'https://cdn.example.com'

        // 获取构建后的文件列表
        const fileList = await glob.sync('./dist/**/*.{js,css,html}')

        // 遍历文件列表
        fileList.forEach((filePath) => {
          // 读取文件内容
          const fileContent = fs.readFileSync(filePath, 'utf-8')

          // 查找并替换所有引用的图片路径
          const newFileContent = fileContent.replace(/(\/images\/)/g, `${cdnBaseUrl}/images/`)

          // 写入修改后的文件内容
          fs.writeFileSync(filePath, newFileContent, 'utf-8')
        })
      },
    },
  },
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
最后更新: 2023/3/2 10:02:33