Skip to content

Commit

Permalink
perf: lazy init vite-node
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz committed Aug 29, 2023
1 parent 4a64775 commit 7ad5b29
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
4 changes: 3 additions & 1 deletion src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ type Macro = CallMacro | IdentifierMacro
export async function transformMacros(
code: string,
id: string,
runner: ViteNodeRunner,
getRunner: () => Promise<ViteNodeRunner>,
deps: Map<string, Set<string>>
) {
const program = babelParse(code, getLang(id), {
Expand Down Expand Up @@ -120,6 +120,8 @@ export async function transformMacros(
return
}

const runner = await getRunner()

deps.set(id, new Set())
for (const macro of macros) {
const {
Expand Down
23 changes: 15 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export default createUnplugin<Options | undefined, false>((rawOptions = {}) => {

const deps: Map<string, Set<string>> = new Map()

let initPromise: Promise<void> | undefined
async function initServer() {
server = await createServer({
...options.viteConfig,
Expand All @@ -29,7 +30,6 @@ export default createUnplugin<Options | undefined, false>((rawOptions = {}) => {
})
await server.pluginContainer.buildStart({})
}

function initRunner() {
// create vite-node server
node = new ViteNodeServer(server)
Expand All @@ -54,19 +54,26 @@ export default createUnplugin<Options | undefined, false>((rawOptions = {}) => {
},
})
}
function init() {
if (initPromise) return initPromise
return (initPromise = (async () => {
server || (await initServer())
initRunner()
})())
}

async function getRunner() {
await init()
return runner
}

const name = 'unplugin-macros'
return {
name,
enforce: options.enforce,

async buildStart() {
server || (await initServer())
initRunner()
},

buildEnd() {
if (builtInServer)
if (builtInServer && server)
// close the built-in vite server
return server.close()
},
Expand All @@ -76,7 +83,7 @@ export default createUnplugin<Options | undefined, false>((rawOptions = {}) => {
},

transform(code, id) {
return transformMacros(code, id, runner, deps)
return transformMacros(code, id, getRunner, deps)
},

vite: {
Expand Down

0 comments on commit 7ad5b29

Please sign in to comment.