Vite.jsの本番環境用のbuildでError: 'fileURLToPath' is not exported by __vite-browser-external, imported by node_modules/local-pkg/dist/shared.mjsを解決したメモ

Vite.jsで本番環境のbuildエラーを解決したときのメモです。

エラーログ

$ npm run build

> frontend@0.0.0 build
> tsc && vite build

vite v3.2.5 building for production...
transforming (155) ../node_modules/axios/lib/platform/browser/index.js

✓ 235 modules transformed.
'fileURLToPath' is not exported by __vite-browser-external, imported by node_modules/local-pkg/dist/shared.mjs
file: /home/dev/projects/node_modules/local-pkg/dist/shared.mjs:41:9
39: import path from "path";
40: import fs, { promises as fsPromises } from "fs";
41: import { fileURLToPath } from "url";
             ^
42:
43: // node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js
error during build:
Error: 'fileURLToPath' is not exported by __vite-browser-external, imported by node_modules/local-pkg/dist/shared.mjs

原因

Vite.jsは、developmentではEsbuildを使用しますが、productionではRolleupを用いてbuildするようで、 Rolleup用のPolyfillを自分で追加しないといけないようです。

解決方法

vite-plugin-node-stdlib-browserをインストールする

https://github.com/sodatea/vite-plugin-node-stdlib-browser

  • npm add node-stdlib-browser
  • npm add -D vite-plugin-node-stdlib-browser
// vite.config.ts
import nodePolyfills from 'vite-plugin-node-stdlib-browser'

export default defineConfig({
  plugins: [nodePolyfills()]
})

参考URL