fix: use worker thread to run rollup again

This commit is contained in:
EGOIST 2021-03-18 22:40:56 +08:00
parent 2aa31d9ec0
commit f6a07fdc0c
3 changed files with 31 additions and 28 deletions

View File

@ -1,5 +1,6 @@
import fs from 'fs'
import { dirname, join, extname } from 'path'
import { Worker } from 'worker_threads'
import colors from 'chalk'
import type { InputOption } from 'rollup'
import { transform as transformToEs5 } from 'buble'
@ -338,8 +339,6 @@ export async function build(_options: Options) {
let existingOnSuccess: ChildProcess | undefined
let esbuildRunning: Promise<void> | undefined
const buildAll = async () => {
if (existingOnSuccess) existingOnSuccess.kill()
@ -375,7 +374,7 @@ export async function build(_options: Options) {
})
watcher.on('all', async (type, file) => {
console.log(makeLabel('CLI', 'info'), `Change detected: ${type} ${file}`)
esbuildRunning = buildAll().catch(handleError)
await buildAll().catch(handleError)
})
}
@ -391,7 +390,20 @@ export async function build(_options: Options) {
throw new Error(`You need to install "typescript" in your project`)
}
const { startRollup } = await import('./rollup')
await startRollup(options, () => esbuildRunning)
const isDev = __filename.endsWith('index.ts')
const worker = new Worker(
join(__dirname, isDev ? './rollup.dev.js' : './rollup.js')
)
worker.postMessage({
options: {
...options, // functions cannot be cloned
esbuildPlugins: undefined,
},
})
worker.on('message', (data) => {
if (data === 'has-error') {
process.exitCode = 1
}
})
}
}

1
src/rollup.dev.js Normal file
View File

@ -0,0 +1 @@
import './rollup'

View File

@ -1,3 +1,4 @@
import { parentPort } from 'worker_threads'
import { InputOptions, OutputOptions, Plugin } from 'rollup'
import { makeLabel, NormalizedOptions } from './'
import dtsPlugin from 'rollup-plugin-dts'
@ -117,26 +118,15 @@ async function runRollup(options: RollupConfig) {
}
}
async function watchRollup(
options: {
inputConfig: InputOptions
outputConfig: OutputOptions
},
waitForEsbuild: WaitForEsbuild
) {
async function watchRollup(options: {
inputConfig: InputOptions
outputConfig: OutputOptions
}) {
const { watch } = await import('rollup')
watch({
...options.inputConfig,
plugins: [
{
name: 'wait-for-esbuild',
async buildStart() {
await waitForEsbuild()
},
},
...(options.inputConfig.plugins || []),
],
plugins: options.inputConfig.plugins,
output: options.outputConfig,
}).on('event', async (event) => {
if (event.code === 'START') {
@ -153,16 +143,16 @@ async function watchRollup(
})
}
type WaitForEsbuild = () => undefined | Promise<void>
export const startRollup = async (
options: NormalizedOptions,
waitForEsbuild: WaitForEsbuild
) => {
const startRollup = async (options: NormalizedOptions) => {
const config = await getRollupConfig(options)
if (options.watch) {
watchRollup(config, waitForEsbuild)
watchRollup(config)
} else {
await runRollup(config)
parentPort?.close()
}
}
parentPort?.on('message', (data) => {
startRollup(data.options)
})