Skip to content

Commit

Permalink
feat: lazy load terser worker
Browse files Browse the repository at this point in the history
  • Loading branch information
agriffis committed Dec 28, 2021
1 parent 3e0e4fd commit 25f7a1f
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions packages/vite/src/node/plugins/terser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,21 @@ import type { Terser } from 'types/terser'
import type { ResolvedConfig } from '..'

export function terserPlugin(config: ResolvedConfig): Plugin {
const worker = new Worker(
(basedir: string, code: string, options: Terser.MinifyOptions) => {
// when vite is linked, the worker thread won't share the same resolve
// root with vite itself, so we have to pass in the basedir and resolve
// terser first.
// eslint-disable-next-line node/no-restricted-require
const terserPath = require.resolve('terser', {
paths: [basedir]
})
return require(terserPath).minify(code, options) as Terser.MinifyOutput
}
)
const makeWorker = () =>
new Worker(
(basedir: string, code: string, options: Terser.MinifyOptions) => {
// when vite is linked, the worker thread won't share the same resolve
// root with vite itself, so we have to pass in the basedir and resolve
// terser first.
// eslint-disable-next-line node/no-restricted-require
const terserPath = require.resolve('terser', {
paths: [basedir]
})
return require(terserPath).minify(code, options) as Terser.MinifyOutput
}
)

let worker: ReturnType<typeof makeWorker>

return {
name: 'vite:terser',
Expand All @@ -33,11 +36,14 @@ export function terserPlugin(config: ResolvedConfig): Plugin {
}

// Do not minify ES lib output since that would remove pure annotations
// and break tree-shaking
// and break tree-shaking.
if (config.build.lib && outputOptions.format === 'es') {
return null
}

// Lazy load worker.
worker ||= makeWorker()

const res = await worker.run(__dirname, code, {
safari10: true,
...config.build.terserOptions,
Expand All @@ -52,7 +58,7 @@ export function terserPlugin(config: ResolvedConfig): Plugin {
},

closeBundle() {
worker.stop()
worker?.stop()
}
}
}

0 comments on commit 25f7a1f

Please sign in to comment.