Fix ESM module loading in Function node

Fixes #3627
This commit is contained in:
Nick O'Leary 2022-06-09 22:11:48 -05:00
parent 3e34d0badb
commit 71a272f0a6
No known key found for this signature in database
GPG Key ID: 4F2157149161A6C9
1 changed files with 8 additions and 2 deletions

View File

@ -11,6 +11,7 @@ const exec = require("@node-red/util").exec;
const log = require("@node-red/util").log;
const hooks = require("@node-red/util").hooks;
const url = require("url");
const { createRequire } = require("module");
const BUILTIN_MODULES = require('module').builtinModules;
@ -139,10 +140,15 @@ function importModule(module) {
}
const externalModuleDir = getInstallDir();
const moduleDir = path.join(externalModuleDir,"node_modules",module);
// To handle both CJS and ESM we need to resolve the module to the
// specific file that is loaded when the module is required/imported
// As this won't be on the natural module search path, we use createRequire
// to access the module
const modulePath = createRequire(moduleDir).resolve(module)
// Import needs the full path to the module's main .js file
// It also needs to be a file:// url for Windows
const moduleFile = url.pathToFileURL(require.resolve(moduleDir));
return import(moduleFile);
const moduleUrl = url.pathToFileURL(modulePath);
return import(moduleUrl);
}
function parseModuleName(module) {