From 30a8c91f72ee49df1c9a96df66112571a39d37ab Mon Sep 17 00:00:00 2001 From: Dorian Date: Fri, 10 Jul 2020 20:56:28 +0800 Subject: [PATCH] fix(commonjs): prevent rewrite require.resolve (#446) --- packages/commonjs/src/transform.js | 12 ++++++++++++ .../test/fixtures/form/ndoe-require-methods/input.js | 3 +++ .../fixtures/form/ndoe-require-methods/output.js | 11 +++++++++++ 3 files changed, 26 insertions(+) create mode 100644 packages/commonjs/test/fixtures/form/ndoe-require-methods/input.js create mode 100644 packages/commonjs/test/fixtures/form/ndoe-require-methods/output.js diff --git a/packages/commonjs/src/transform.js b/packages/commonjs/src/transform.js index 8af4547e2..8fe5cf49c 100644 --- a/packages/commonjs/src/transform.js +++ b/packages/commonjs/src/transform.js @@ -192,6 +192,14 @@ export function transformCommonjs( return true; } + function isNodeRequireStatement(parent) { + const reservedMethod = ['resolve', 'cache', 'main']; + if (parent && parent.property && reservedMethod.indexOf(parent.property.name) > -1) { + return true; + } + return false; + } + function isIgnoredRequireStatement(requiredNode) { return ignoreRequire(requiredNode.arguments[0].value); } @@ -353,6 +361,10 @@ export function transformCommonjs( if (isReference(node, parent) && !scope.contains(node.name)) { if (node.name in uses) { if (isRequireIdentifier(node)) { + if (isNodeRequireStatement(parent)) { + return; + } + if (!isDynamicRequireModulesEnabled && isStaticRequireStatement(parent)) { return; } diff --git a/packages/commonjs/test/fixtures/form/ndoe-require-methods/input.js b/packages/commonjs/test/fixtures/form/ndoe-require-methods/input.js new file mode 100644 index 000000000..40e9a2f48 --- /dev/null +++ b/packages/commonjs/test/fixtures/form/ndoe-require-methods/input.js @@ -0,0 +1,3 @@ +module.exports.getFilePath = function getFilePath(someFile) { + return require.resolve(someFile); +}; diff --git a/packages/commonjs/test/fixtures/form/ndoe-require-methods/output.js b/packages/commonjs/test/fixtures/form/ndoe-require-methods/output.js new file mode 100644 index 000000000..9b45c500c --- /dev/null +++ b/packages/commonjs/test/fixtures/form/ndoe-require-methods/output.js @@ -0,0 +1,11 @@ +var getFilePath = function getFilePath(someFile) { + return require.resolve(someFile); +}; + +var input = { + getFilePath: getFilePath +}; + +export default input; +export { input as __moduleExports }; +export { getFilePath }; \ No newline at end of file