Skip to content

Commit 21ba493

Browse files
authored
perf: use lazy require in vm pool (#4136)
1 parent d284e12 commit 21ba493

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

packages/vitest/src/runtime/vm/commonjs-executor.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ interface PrivateNodeModule extends NodeModule {
1919
_compile(code: string, filename: string): void
2020
}
2121

22+
const requiresCache = new WeakMap<NodeModule, NodeRequire>()
23+
2224
export class CommonjsExecutor {
2325
private context: vm.Context
2426
private requireCache = new Map<string, NodeModule>()
@@ -46,7 +48,6 @@ export class CommonjsExecutor {
4648
this.Module = class Module {
4749
exports: any
4850
isPreloading = false
49-
require: NodeRequire
5051
id: string
5152
filename: string
5253
loaded: boolean
@@ -55,9 +56,8 @@ export class CommonjsExecutor {
5556
path: string
5657
paths: string[] = []
5758

58-
constructor(id: string, parent?: Module) {
59+
constructor(id = '', parent?: Module) {
5960
this.exports = primitives.Object.create(Object.prototype)
60-
this.require = Module.createRequire(id)
6161
// in our case the path should always be resolved already
6262
this.path = dirname(id)
6363
this.id = id
@@ -66,6 +66,16 @@ export class CommonjsExecutor {
6666
this.parent = parent
6767
}
6868

69+
get require() {
70+
const require = requiresCache.get(this)
71+
if (require)
72+
return require
73+
74+
const _require = Module.createRequire(this.id)
75+
requiresCache.set(this, _require)
76+
return _require
77+
}
78+
6979
_compile(code: string, filename: string) {
7080
const cjsModule = Module.wrap(code)
7181
const script = new vm.Script(cjsModule, {

test/vm-threads/test/module.test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { Module } from 'node:module'
2+
import { expect, it } from 'vitest'
3+
4+
it('can create modules with incorrect filepath', () => {
5+
expect(() => new Module('name')).not.toThrow()
6+
// require will not work for these modules because native createRequire fails
7+
expect(() => new Module('some-other-name').require('node:url')).toThrow()
8+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy