记录vite 处理worker打包输出目录

75 阅读1分钟

worker文件比如demo.worker.js会被vite默认处理为asset资源,会被默认输出到目录assets中,无法通过rollupOptions的chunkFileNames,entryFileNames,assetFileNames去处理输出目录。

解决方法是通过插件的形式,处理所有worker相关的文件。其中,不仅要处理输出目录,还得处理输出目录变更后文件内请求地址变更的问题,以下是解决方式。

export function customWorkerOutput() {
  return {
    name: 'custom-worker-output',
    generateBundle(options, bundle) {
      for (const fileName in bundle) {
        const asset = bundle[fileName]
        // 更改输出目录
        if (fileName.includes('.worker')) {
          const newFileName = asset.fileName.replace(/^assets\//, '')
          asset.fileName = `js/${newFileName}`
        }
        
        if (asset.fileName.includes('.worker')) {
          // 修改文件中的worker路径,防止修改输出目录后,worker路径错误
          // config.publicPath是自己的项目路由
          asset.code = asset.code.replace(/new Worker\(new URL\("\/assets\/(.+?\.worker[^"]+)",\s*import\.meta\.url\)\)/g, `new Worker(new URL("${config.publicPath}/js/$1", import.meta.url))`)
        }
      }
    }
  }
}

使用

plugins: [
    vue(),
    customWorkerOutput()
],