Skip to content

Commit

Permalink
Support conditional export resolution with custom resolver
Browse files Browse the repository at this point in the history
  • Loading branch information
nick-klaviyo committed Feb 2, 2023
1 parent e7828cf commit 5a86675
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/resolver-compat.js
Original file line number Diff line number Diff line change
Expand Up @@ -322,8 +322,13 @@ function resolverFromOptions(vm, options, override, compiler) {
}
const resolved = customResolver(x, path);
if (!resolved) return undefined;
if (externals) externals.push(new RegExp('^' + escapeRegExp(resolved)));
return resolver.loadAsFileOrDirecotry(resolved, extList);
if (typeof resolved === 'string') {
if (externals) externals.push(new RegExp('^' + escapeRegExp(resolved)));
return resolver.loadAsFileOrDirecotry(resolved, extList);
}
const {module=x, path: resolvedPath} = resolved;
if (externals) externals.push(new RegExp('^' + escapeRegExp(resolvedPath)));
return resolver.loadNodeModules(module, [resolvedPath], extList);
};
}

Expand Down
1 change: 1 addition & 0 deletions test/additional-modules/my-es-module/index.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = {additional_cjs_module: true};
1 change: 1 addition & 0 deletions test/additional-modules/my-es-module/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default {additional_es_module: true};
11 changes: 11 additions & 0 deletions test/additional-modules/my-es-module/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"main": "index.js",
"exports": {
".": {
"default": {
"require": "./index.cjs",
"default": "./index.js"
}
}
}
}
11 changes: 11 additions & 0 deletions test/nodevm.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,17 @@ describe('modules', () => {
assert.ok(vm.run("require('my-module')", __filename));
});

it('can resolve conditional exports with a custom resolver', () => {
const vm = new NodeVM({
require: {
external: ['my-es-module'],
resolve: () => ({ path: path.resolve(__dirname, 'additional-modules') })
}
});

assert.ok(vm.run("require('my-es-module')", __filename));
})

it('allows for multiple root folders', () => {
const vm = new NodeVM({
require: {
Expand Down

0 comments on commit 5a86675

Please sign in to comment.