Skip to content

Commit

Permalink
perf: use lazy require in vm pool (#4136)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Sep 18, 2023
1 parent d284e12 commit 21ba493
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
16 changes: 13 additions & 3 deletions packages/vitest/src/runtime/vm/commonjs-executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ interface PrivateNodeModule extends NodeModule {
_compile(code: string, filename: string): void
}

const requiresCache = new WeakMap<NodeModule, NodeRequire>()

export class CommonjsExecutor {
private context: vm.Context
private requireCache = new Map<string, NodeModule>()
Expand Down Expand Up @@ -46,7 +48,6 @@ export class CommonjsExecutor {
this.Module = class Module {
exports: any
isPreloading = false
require: NodeRequire
id: string
filename: string
loaded: boolean
Expand All @@ -55,9 +56,8 @@ export class CommonjsExecutor {
path: string
paths: string[] = []

constructor(id: string, parent?: Module) {
constructor(id = '', parent?: Module) {
this.exports = primitives.Object.create(Object.prototype)
this.require = Module.createRequire(id)
// in our case the path should always be resolved already
this.path = dirname(id)
this.id = id
Expand All @@ -66,6 +66,16 @@ export class CommonjsExecutor {
this.parent = parent
}

get require() {
const require = requiresCache.get(this)
if (require)
return require

const _require = Module.createRequire(this.id)
requiresCache.set(this, _require)
return _require
}

_compile(code: string, filename: string) {
const cjsModule = Module.wrap(code)
const script = new vm.Script(cjsModule, {
Expand Down
8 changes: 8 additions & 0 deletions test/vm-threads/test/module.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from 'node:module'
import { expect, it } from 'vitest'

it('can create modules with incorrect filepath', () => {
expect(() => new Module('name')).not.toThrow()
// require will not work for these modules because native createRequire fails
expect(() => new Module('some-other-name').require('node:url')).toThrow()
})

0 comments on commit 21ba493

Please sign in to comment.