From fc710ff53b7e678c9997293374029337ac834139 Mon Sep 17 00:00:00 2001 From: Hong-Kuan Wu Date: Fri, 3 Jan 2025 00:43:03 +0800 Subject: [PATCH] feat: support `module.createRequire` (#459) ## Description Added support for tracing dependencies loaded via `module.createRequire`. Fixes #430 --- src/analyze.ts | 14 ++++++++++++++ test/unit/module-create-require/input.js | 4 ++++ test/unit/module-create-require/lib.node | 1 + test/unit/module-create-require/output.js | 5 +++++ 4 files changed, 24 insertions(+) create mode 100644 test/unit/module-create-require/input.js create mode 100644 test/unit/module-create-require/lib.node create mode 100644 test/unit/module-create-require/output.js diff --git a/src/analyze.ts b/src/analyze.ts index 9f33e76e..6ea325eb 100644 --- a/src/analyze.ts +++ b/src/analyze.ts @@ -1082,6 +1082,20 @@ export default async function analyze( if (returned) setKnownBinding(fnName.name, { value: BOUND_REQUIRE }); } } + // Support module.createRequire + if ( + node.type === 'CallExpression' && + node.callee.type === 'MemberExpression' && + node.callee.object.type === 'Identifier' && + node.callee.object.name === 'module' && + node.callee.property.type === 'Identifier' && + node.callee.property.name === 'createRequire' + ) { + if (parent.type === 'VariableDeclarator') { + const requireName = parent.id.name; + setKnownBinding(requireName, { value: BOUND_REQUIRE }); + } + } }, async leave(_node, _parent) { const node: Node = _node as any; diff --git a/test/unit/module-create-require/input.js b/test/unit/module-create-require/input.js new file mode 100644 index 00000000..a2ff1279 --- /dev/null +++ b/test/unit/module-create-require/input.js @@ -0,0 +1,4 @@ +import * as module from 'node:module'; + +const req = module.createRequire(import.meta.url); +const lib = req('./lib.node'); \ No newline at end of file diff --git a/test/unit/module-create-require/lib.node b/test/unit/module-create-require/lib.node new file mode 100644 index 00000000..7edc5b92 --- /dev/null +++ b/test/unit/module-create-require/lib.node @@ -0,0 +1 @@ +// Native module for testing \ No newline at end of file diff --git a/test/unit/module-create-require/output.js b/test/unit/module-create-require/output.js new file mode 100644 index 00000000..985cdfa1 --- /dev/null +++ b/test/unit/module-create-require/output.js @@ -0,0 +1,5 @@ +[ + "package.json", + "test/unit/module-create-require/input.js", + "test/unit/module-create-require/lib.node" +] \ No newline at end of file