1
0
mirror of https://github.com/node-red/node-red.git synced 2023-10-10 13:36:53 +02:00

Merge pull request #3645 from node-red/fix-esm

Fix ESM module loading in Function node
This commit is contained in:
Nick O'Leary 2022-06-13 08:10:28 -05:00 committed by GitHub
commit 8cec0d8fcd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -11,6 +11,7 @@ const exec = require("@node-red/util").exec;
const log = require("@node-red/util").log; const log = require("@node-red/util").log;
const hooks = require("@node-red/util").hooks; const hooks = require("@node-red/util").hooks;
const url = require("url"); const url = require("url");
const { createRequire } = require("module");
const BUILTIN_MODULES = require('module').builtinModules; const BUILTIN_MODULES = require('module').builtinModules;
@ -139,10 +140,15 @@ function importModule(module) {
} }
const externalModuleDir = getInstallDir(); const externalModuleDir = getInstallDir();
const moduleDir = path.join(externalModuleDir,"node_modules",module); 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 // Import needs the full path to the module's main .js file
// It also needs to be a file:// url for Windows // It also needs to be a file:// url for Windows
const moduleFile = url.pathToFileURL(require.resolve(moduleDir)); const moduleUrl = url.pathToFileURL(modulePath);
return import(moduleFile); return import(moduleUrl);
} }
function parseModuleName(module) { function parseModuleName(module) {