@@ -4,29 +4,46 @@ import type { Terser } from 'types/terser'
44import type { ResolvedConfig } from '..'
55
66export function terserPlugin ( config : ResolvedConfig ) : Plugin {
7- const worker = new Worker (
8- ( basedir : string , code : string , options : Terser . MinifyOptions ) => {
9- // when vite is linked, the worker thread won't share the same resolve
10- // root with vite itself, so we have to pass in the basedir and resolve
11- // terser first.
12- // eslint-disable-next-line node/no-restricted-require
13- const terserPath = require . resolve ( 'terser' , {
14- paths : [ basedir ]
15- } )
16- return require ( terserPath ) . minify ( code , options ) as Terser . MinifyOutput
17- }
18- )
7+ const makeWorker = ( ) =>
8+ new Worker (
9+ ( basedir : string , code : string , options : Terser . MinifyOptions ) => {
10+ // when vite is linked, the worker thread won't share the same resolve
11+ // root with vite itself, so we have to pass in the basedir and resolve
12+ // terser first.
13+ // eslint-disable-next-line node/no-restricted-require
14+ const terserPath = require . resolve ( 'terser' , {
15+ paths : [ basedir ]
16+ } )
17+ return require ( terserPath ) . minify ( code , options ) as Terser . MinifyOutput
18+ }
19+ )
20+
21+ let worker : ReturnType < typeof makeWorker >
1922
2023 return {
2124 name : 'vite:terser' ,
2225
2326 async renderChunk ( code , _chunk , outputOptions ) {
27+ // This plugin is included for any non-false value of config.build.minify,
28+ // so that normal chunks can use the preferred minifier, and legacy chunks
29+ // can use terser.
30+ if (
31+ config . build . minify !== 'terser' &&
32+ // @ts -ignore injected by @vitejs/plugin-legacy
33+ ! outputOptions . __vite_force_terser__
34+ ) {
35+ return null
36+ }
37+
2438 // Do not minify ES lib output since that would remove pure annotations
25- // and break tree-shaking
39+ // and break tree-shaking.
2640 if ( config . build . lib && outputOptions . format === 'es' ) {
2741 return null
2842 }
2943
44+ // Lazy load worker.
45+ worker ||= makeWorker ( )
46+
3047 const res = await worker . run ( __dirname , code , {
3148 safari10 : true ,
3249 ...config . build . terserOptions ,
@@ -41,7 +58,7 @@ export function terserPlugin(config: ResolvedConfig): Plugin {
4158 } ,
4259
4360 closeBundle ( ) {
44- worker . stop ( )
61+ worker ? .stop ( )
4562 }
4663 }
4764}
0 commit comments