@@ -4,29 +4,46 @@ import type { Terser } from 'types/terser'
4
4
import type { ResolvedConfig } from '..'
5
5
6
6
export 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 >
19
22
20
23
return {
21
24
name : 'vite:terser' ,
22
25
23
26
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
+
24
38
// Do not minify ES lib output since that would remove pure annotations
25
- // and break tree-shaking
39
+ // and break tree-shaking.
26
40
if ( config . build . lib && outputOptions . format === 'es' ) {
27
41
return null
28
42
}
29
43
44
+ // Lazy load worker.
45
+ worker ||= makeWorker ( )
46
+
30
47
const res = await worker . run ( __dirname , code , {
31
48
safari10 : true ,
32
49
...config . build . terserOptions ,
@@ -41,7 +58,7 @@ export function terserPlugin(config: ResolvedConfig): Plugin {
41
58
} ,
42
59
43
60
closeBundle ( ) {
44
- worker . stop ( )
61
+ worker ? .stop ( )
45
62
}
46
63
}
47
64
}
0 commit comments