diff --git a/package.json b/package.json index fc5a376..e6fc97f 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "type": "module", "main": "retrieveGlobals.js", "scripts": { - "test": "npx ava" + "test": "NODE_OPTIONS='--experimental-vm-modules' npx ava" }, "repository": { "type": "git", diff --git a/retrieveGlobals.js b/retrieveGlobals.js index 8df9caf..806f351 100644 --- a/retrieveGlobals.js +++ b/retrieveGlobals.js @@ -35,7 +35,10 @@ class RetrieveGlobals { // to `const ___ = await import(___)` // to emulate *some* import syntax. // Doesn’t currently work with aliases (mod as name) or namespaced imports (* as name). - if(this.options.transformEsmImports) { + if(this.options.transformEsmImports === "require") { + let it = new ImportTransformer(this.originalCode); + this.code = it.transformToRequire(); + } else if(this.options.transformEsmImports) { let it = new ImportTransformer(this.originalCode); this.code = it.transformToDynamicImport(); } else { diff --git a/test/test.js b/test/test.js index dc56a1a..1bbe065 100644 --- a/test/test.js +++ b/test/test.js @@ -100,15 +100,6 @@ test("destructured assignment via Array", async t => { t.is(ret.b, 2); }); - -test("dynamic import", async t => { - let vm = new RetrieveGlobals(`const { noop } = await import("@zachleat/noop");`); - let ret = await vm.getGlobalContext(undefined, { - dynamicImport: true - }); - t.is(typeof ret.noop, "function"); -}); - test("global: same console.log", async t => { let vm = new RetrieveGlobals(`const b = console.log`); let ret = await vm.getGlobalContext(undefined, { @@ -147,14 +138,41 @@ const b = 1;`); t.is(ret.b, 1); }); -test("ESM import", async t => { +test("dynamic import (no code transformation) (requires --experimental-vm-modules in Node v20.10)", async t => { + let vm = new RetrieveGlobals(`const { noop } = await import("@zachleat/noop");`); + let ret = await vm.getGlobalContext(undefined, { + dynamicImport: true + }); + t.is(typeof ret.noop, "function"); +}); + +test("ESM import (requires --experimental-vm-modules in Node v20.10)", async t => { let vm = new RetrieveGlobals(`import { noop } from "@zachleat/noop"; const b = 1;`, { transformEsmImports: true, }); let ret = await vm.getGlobalContext(undefined, { - dynamicImport: true + dynamicImport: true, }); t.is(typeof ret.noop, "function"); t.is(ret.b, 1); -}); \ No newline at end of file +}); + +test("ESM import (fallback to `require`)", async t => { + let vm = new RetrieveGlobals(`import { noop } from "@zachleat/noop"; +const b = 1;`, { + transformEsmImports: "require", + }); + + let ret = await vm.getGlobalContext(undefined, { + addRequire: true, + }); + + t.is(typeof ret.noop, "function"); + t.is(ret.b, 1); +}); + +// test("__filename", t => { +// let vm = new RetrieveGlobals("var b = __filename;"); +// t.deepEqual(vm.getGlobalContextSync({}, { reuseGlobal: true }), { b: __filename }); +// }); \ No newline at end of file