Skip to content

Commit

Permalink
fix(commonjs): inject module name into dynamic require function (#1038)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukastaegert committed Apr 24, 2022
1 parent df01795 commit 0b9a0e8
Show file tree
Hide file tree
Showing 21 changed files with 499 additions and 351 deletions.
35 changes: 19 additions & 16 deletions packages/commonjs/src/dynamic-modules.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,17 @@ export function getDynamicRequireModules(patterns, dynamicRequireRoot) {

const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;

export const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire';
export const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire';

export function getDynamicModuleRegistry(
isDynamicRequireModulesEnabled,
dynamicRequireModules,
commonDir,
ignoreDynamicRequires
) {
if (!isDynamicRequireModulesEnabled) {
return `export function commonjsRequire(path) {
return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
${FAILED_REQUIRE_ERROR}
}`;
}
Expand Down Expand Up @@ -100,25 +103,25 @@ ${dynamicModuleProps}
});
}
export function commonjsRequire(path, originalModuleDir) {
var resolvedPath = commonjsResolveImpl(path, originalModuleDir);
if (resolvedPath !== null) {
return getDynamicModules()[resolvedPath]();
export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
function handleRequire(path) {
var resolvedPath = commonjsResolve(path, originalModuleDir);
if (resolvedPath !== null) {
return getDynamicModules()[resolvedPath]();
}
${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
}
${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
}
function commonjsResolve (path, originalModuleDir) {
const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
if (resolvedPath !== null) {
return resolvedPath;
handleRequire.resolve = function (path) {
var resolvedPath = commonjsResolve(path, originalModuleDir);
if (resolvedPath !== null) {
return resolvedPath;
}
return require.resolve(path);
}
return require.resolve(path);
return handleRequire;
}
commonjsRequire.resolve = commonjsResolve;
function commonjsResolveImpl (path, originalModuleDir) {
function commonjsResolve (path, originalModuleDir) {
var shouldTryNodeModules = isPossibleNodeModulesPath(path);
path = normalize(path);
var relPath;
Expand Down
9 changes: 6 additions & 3 deletions packages/commonjs/src/generate-imports.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { COMMONJS_REQUIRE_EXPORT, CREATE_COMMONJS_REQUIRE_EXPORT } from './dynamic-modules';
import {
DYNAMIC_MODULES_ID,
EXPORTS_SUFFIX,
Expand Down Expand Up @@ -92,14 +93,16 @@ export function getRequireHandlers() {
resolveRequireSourcesAndGetMeta,
needsRequireWrapper,
isEsModule,
usesRequire,
isDynamicRequireModulesEnabled,
getIgnoreTryCatchRequireStatementMode
) {
const imports = [];
imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
if (usesRequire) {
if (dynamicRequireName) {
imports.push(
`import { commonjsRequire as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
`import { ${
isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
} as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
);
}
if (exportMode === 'module') {
Expand Down
38 changes: 20 additions & 18 deletions packages/commonjs/src/transform-commonjs.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
isTruthy,
KEY_COMPILED_ESM
} from './ast-utils';
import { COMMONJS_REQUIRE_EXPORT, CREATE_COMMONJS_REQUIRE_EXPORT } from './dynamic-modules';
import { rewriteExportsAndGetExportsBlock, wrapCode } from './generate-exports';
import {
getRequireHandlers,
Expand Down Expand Up @@ -201,12 +202,6 @@ export default async function transformCommonjs(
checkDynamicRequire(node.start);
uses.require = true;
const requireNode = node.callee.object;
magicString.appendLeft(
node.end - 1,
`,${JSON.stringify(
dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
)}`
);
replacedDynamicRequires.push(requireNode);
return;
}
Expand All @@ -221,12 +216,6 @@ export default async function transformCommonjs(
if (hasDynamicArguments(node)) {
if (isDynamicRequireModulesEnabled) {
checkDynamicRequire(node.start);
magicString.appendLeft(
node.end - 1,
`, ${JSON.stringify(
dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
)}`
);
}
if (!ignoreDynamicRequires) {
replacedDynamicRequires.push(node.callee);
Expand Down Expand Up @@ -400,7 +389,13 @@ export default async function transformCommonjs(
const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
const helpersName = deconflict([scope], globals, 'commonjsHelpers');
const dynamicRequireName = deconflict([scope], globals, 'commonjsRequire');
const dynamicRequireName =
replacedDynamicRequires.length > 0 &&
deconflict(
[scope],
globals,
isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
);
const deconflictedExportNames = Object.create(null);
for (const [exportName, { scopes }] of exportsAssignmentsByName) {
deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
Expand All @@ -412,10 +407,17 @@ export default async function transformCommonjs(
});
}
for (const node of replacedDynamicRequires) {
magicString.overwrite(node.start, node.end, dynamicRequireName, {
contentOnly: true,
storeName: true
});
magicString.overwrite(
node.start,
node.end,
isDynamicRequireModulesEnabled
? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
: dynamicRequireName,
{
contentOnly: true,
storeName: true
}
);
}

// We cannot wrap ES/mixed modules
Expand Down Expand Up @@ -470,7 +472,7 @@ export default async function transformCommonjs(
resolveRequireSourcesAndGetMeta,
needsRequireWrapper,
isEsModule,
uses.require,
isDynamicRequireModulesEnabled,
getIgnoreTryCatchRequireStatementMode
);
const exportBlock = isEsModule
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input } from "\u0000fixtures/form/constant-template-literal/input.js?commonjs-exports"
import require$$0 from "\u0000CWD/fixtures/form/constant-template-literal/tape.js?commonjs-proxy";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input } from "\u0000fixtures/form/ignore-ids-function/input.js?commonjs-exports"
import require$$0 from "\u0000CWD/fixtures/form/ignore-ids-function/bar.js?commonjs-proxy";

Expand Down
1 change: 0 additions & 1 deletion packages/commonjs/test/fixtures/form/ignore-ids/output.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input } from "\u0000fixtures/form/ignore-ids/input.js?commonjs-exports"
import require$$0 from "\u0000CWD/fixtures/form/ignore-ids/bar.js?commonjs-proxy";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import require$$0 from "\u0000CWD/fixtures/form/multi-entry-module-exports/input2.js?commonjs-proxy";

const t2 = require$$0;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input } from "\u0000fixtures/form/multiple-var-declarations-b/input.js?commonjs-exports"
import require$$0 from "\u0000CWD/fixtures/form/multiple-var-declarations-b/a.js?commonjs-proxy";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input } from "\u0000fixtures/form/multiple-var-declarations-c/input.js?commonjs-exports"
import require$$0 from "\u0000CWD/fixtures/form/multiple-var-declarations-c/b.js?commonjs-proxy";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input } from "\u0000fixtures/form/multiple-var-declarations/input.js?commonjs-exports"
import require$$0 from "\u0000CWD/fixtures/form/multiple-var-declarations/a.js?commonjs-proxy";
import require$$1 from "\u0000CWD/fixtures/form/multiple-var-declarations/b.js?commonjs-proxy";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input_1 } from "\u0000fixtures/form/no-exports-entry/input.js?commonjs-exports"
import require$$0 from "\u0000CWD/fixtures/form/no-exports-entry/dummy.js?commonjs-proxy";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input } from "\u0000fixtures/form/node-require-methods/input.js?commonjs-exports"

var getFilePath = input.getFilePath = function getFilePath(someFile) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input } from "\u0000fixtures/form/require-collision/input.js?commonjs-exports"
import require$$1 from "\u0000CWD/fixtures/form/require-collision/foo.js?commonjs-proxy";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input } from "\u0000fixtures/form/unambiguous-with-default-export/input.js?commonjs-exports"
import "\u0000CWD/fixtures/form/unambiguous-with-default-export/foo.js?commonjs-proxy";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input } from "\u0000fixtures/form/unambiguous-with-import/input.js?commonjs-exports"
import "\u0000CWD/fixtures/form/unambiguous-with-import/foo.js?commonjs-proxy";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as commonjsHelpers from "_commonjsHelpers.js";
import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules";
import { __exports as input } from "\u0000fixtures/form/unambiguous-with-named-export/input.js?commonjs-exports"
import "\u0000CWD/fixtures/form/unambiguous-with-named-export/foo.js?commonjs-proxy";

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
description: 'resolves both windows and posix paths',
pluginOptions: {
dynamicRequireTargets: ['fixtures/function/dynamic-require-alias-hack/stub.js'],
ignoreDynamicRequires: true
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/* eslint-disable global-require */
// noinspection UnnecessaryLocalVariableJS

// A hack used in many old libraries, saying "workaround to exclude package from browserify list."
// Will bypass rollup-commonjs finding out that this is a require that should not go through the plugin, and will do an infinite search.
const _require = require;
const buffer = _require('buffer');

t.is(buffer, require('buffer'));
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = function () {
return 'Hello there';
};
Loading

0 comments on commit 0b9a0e8

Please sign in to comment.