Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: use lazy require in vm pool #4136

Merged
merged 1 commit into from Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 13 additions & 3 deletions packages/vitest/src/runtime/vm/commonjs-executor.ts
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
@@ -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()
})