diff --git a/packages/vite/src/node/plugins/terser.ts b/packages/vite/src/node/plugins/terser.ts index 3ead4b3ad06dda..e94fd792e51249 100644 --- a/packages/vite/src/node/plugins/terser.ts +++ b/packages/vite/src/node/plugins/terser.ts @@ -1,14 +1,17 @@ +import { pathToFileURL } from 'url' import { Worker } from 'okie' import type { Terser } from 'types/terser' import type { Plugin } from '../plugin' import type { ResolvedConfig } from '..' import { requireResolveFromRootWithFallback } from '../utils' -let terserPath: string | undefined -const loadTerserPath = (root: string) => { - if (terserPath) return terserPath +let terserFileUrl: URL | undefined +const loadTerserFileUrl = (root: string) => { + if (terserFileUrl) return terserFileUrl try { - terserPath = requireResolveFromRootWithFallback(root, 'terser') + terserFileUrl = pathToFileURL( + requireResolveFromRootWithFallback(root, 'terser') + ) } catch (e) { if (e.code === 'MODULE_NOT_FOUND') { throw new Error( @@ -20,19 +23,18 @@ const loadTerserPath = (root: string) => { throw message } } - return terserPath + return terserFileUrl } export function terserPlugin(config: ResolvedConfig): Plugin { const makeWorker = () => new Worker( async ( - terserPath: string, + terserFileUrl: string, code: string, options: Terser.MinifyOptions ) => { - // eslint-disable-next-line no-restricted-globals -- this function runs inside cjs - const terser = require(terserPath) + const terser = await import(terserFileUrl) return terser.minify(code, options) as Terser.MinifyOutput } ) @@ -63,8 +65,8 @@ export function terserPlugin(config: ResolvedConfig): Plugin { // Lazy load worker. worker ||= makeWorker() - const terserPath = loadTerserPath(config.root) - const res = await worker.run(terserPath, code, { + const terserFileUrl = loadTerserFileUrl(config.root) + const res = await worker.run(terserFileUrl.href, code, { safari10: true, ...config.build.terserOptions, sourceMap: !!outputOptions.sourcemap,