diff --git a/packages/commonjs/package.json b/packages/commonjs/package.json index ca6f51bed..865e1f98f 100644 --- a/packages/commonjs/package.json +++ b/packages/commonjs/package.json @@ -16,7 +16,7 @@ "main": "dist/index.js", "module": "dist/index.es.js", "engines": { - "node": ">= 8.0.0" + "node": ">= 12.0.0" }, "scripts": { "build": "rollup -c", diff --git a/packages/commonjs/src/dynamic-modules.js b/packages/commonjs/src/dynamic-modules.js new file mode 100644 index 000000000..02b9845f3 --- /dev/null +++ b/packages/commonjs/src/dynamic-modules.js @@ -0,0 +1,144 @@ +import { getVirtualPathForDynamicRequirePath, normalizePathSlashes } from './utils'; + +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 function getDynamicRequireModules( + isDynamicRequireModulesEnabled, + dynamicRequireModuleSet, + commonDir, + ignoreDynamicRequires +) { + if (!isDynamicRequireModulesEnabled) { + return `export function commonjsRequire(path) { + ${FAILED_REQUIRE_ERROR} +}`; + } + const dynamicModuleIds = [...dynamicRequireModuleSet]; + const dynamicModuleImports = dynamicModuleIds + .map( + (id, index) => + `import ${ + id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }` + } from ${JSON.stringify(id)};` + ) + .join('\n'); + const dynamicModuleProps = dynamicModuleIds + .map( + (id, index) => + `\t\t${JSON.stringify( + getVirtualPathForDynamicRequirePath(normalizePathSlashes(id), commonDir) + )}: ${id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}`}` + ) + .join(',\n'); + return `${dynamicModuleImports} + +var dynamicModules; + +function getDynamicModules() { + return dynamicModules || (dynamicModules = { +${dynamicModuleProps} + }); +} + +export function commonjsRequire(path, originalModuleDir) { + var resolvedPath = commonjsResolveImpl(path, originalModuleDir, true); + if (resolvedPath !== null) { + return getDynamicModules()[resolvedPath](); + } + ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR} +} + +function commonjsResolve (path, originalModuleDir) { + const resolvedPath = commonjsResolveImpl(path, originalModuleDir); + if (resolvedPath !== null) { + return resolvedPath; + } + return require.resolve(path); +} + +commonjsRequire.resolve = commonjsResolve; + +function commonjsResolveImpl (path, originalModuleDir) { + var shouldTryNodeModules = isPossibleNodeModulesPath(path); + path = normalize(path); + var relPath; + if (path[0] === '/') { + originalModuleDir = '/'; + } + var modules = getDynamicModules(); + var checkedExtensions = ['', '.js', '.json']; + while (true) { + if (!shouldTryNodeModules) { + relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path; + } else if (originalModuleDir) { + relPath = normalize(originalModuleDir + '/node_modules/' + path); + } else { + relPath = normalize(join('node_modules', path)); + } + + if (relPath.endsWith('/..')) { + break; // Travelled too far up, avoid infinite loop + } + + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) { + var resolvedPath = relPath + checkedExtensions[extensionIndex]; + if (modules[resolvedPath]) { + return resolvedPath; + } + } + if (!shouldTryNodeModules) break; + var nextDir = normalize(originalModuleDir + '/..'); + if (nextDir === originalModuleDir) break; + originalModuleDir = nextDir; + } + return null; +} + +function isPossibleNodeModulesPath (modulePath) { + var c0 = modulePath[0]; + if (c0 === '/' || c0 === '\\\\') return false; + var c1 = modulePath[1], c2 = modulePath[2]; + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) || + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false; + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false; + return true; +} + +function normalize (path) { + path = path.replace(/\\\\/g, '/'); + var parts = path.split('/'); + var slashed = parts[0] === ''; + for (var i = 1; i < parts.length; i++) { + if (parts[i] === '.' || parts[i] === '') { + parts.splice(i--, 1); + } + } + for (var i = 1; i < parts.length; i++) { + if (parts[i] !== '..') continue; + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') { + parts.splice(--i, 2); + i--; + } + } + path = parts.join('/'); + if (slashed && path[0] !== '/') path = '/' + path; + else if (path.length === 0) path = '.'; + return path; +} + +function join () { + if (arguments.length === 0) return '.'; + var joined; + for (var i = 0; i < arguments.length; ++i) { + var arg = arguments[i]; + if (arg.length > 0) { + if (joined === undefined) + joined = arg; + else + joined += '/' + arg; + } + } + if (joined === undefined) return '.'; + return joined; +}`; +} diff --git a/packages/commonjs/src/dynamic-packages-manager.js b/packages/commonjs/src/dynamic-packages-manager.js deleted file mode 100644 index 4e754850b..000000000 --- a/packages/commonjs/src/dynamic-packages-manager.js +++ /dev/null @@ -1,56 +0,0 @@ -import { existsSync, readFileSync } from 'fs'; -import { join } from 'path'; - -import { DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX, HELPERS_ID, wrapId } from './helpers'; -import { getVirtualPathForDynamicRequirePath, normalizePathSlashes } from './utils'; - -export function getPackageEntryPoint(dirPath) { - let entryPoint = 'index.js'; - - try { - if (existsSync(join(dirPath, 'package.json'))) { - entryPoint = - JSON.parse(readFileSync(join(dirPath, 'package.json'), { encoding: 'utf8' })).main || - entryPoint; - } - } catch (ignored) { - // ignored - } - - return entryPoint; -} - -export function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) { - let code = `const commonjsRegisterOrShort = require('${HELPERS_ID}?commonjsRegisterOrShort');`; - for (const dir of dynamicRequireModuleDirPaths) { - const entryPoint = getPackageEntryPoint(dir); - - code += `\ncommonjsRegisterOrShort(${JSON.stringify( - getVirtualPathForDynamicRequirePath(dir, commonDir) - )}, ${JSON.stringify(getVirtualPathForDynamicRequirePath(join(dir, entryPoint), commonDir))});`; - } - return code; -} - -export function getDynamicPackagesEntryIntro( - dynamicRequireModuleDirPaths, - dynamicRequireModuleSet -) { - let dynamicImports = Array.from( - dynamicRequireModuleSet, - (dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});` - ).join('\n'); - - if (dynamicRequireModuleDirPaths.length) { - dynamicImports += `require(${JSON.stringify( - wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX) - )});`; - } - - return dynamicImports; -} - -export function isDynamicModuleImport(id, dynamicRequireModuleSet) { - const normalizedPath = normalizePathSlashes(id); - return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json'); -} diff --git a/packages/commonjs/src/dynamic-require-paths.js b/packages/commonjs/src/dynamic-require-paths.js index f944a0d33..849ab1a9e 100644 --- a/packages/commonjs/src/dynamic-require-paths.js +++ b/packages/commonjs/src/dynamic-require-paths.js @@ -1,11 +1,25 @@ -import { statSync } from 'fs'; - +import { existsSync, readFileSync, statSync } from 'fs'; import { join, resolve } from 'path'; import glob from 'glob'; import { normalizePathSlashes } from './utils'; -import { getPackageEntryPoint } from './dynamic-packages-manager'; + +function getPackageEntryPoint(dirPath) { + let entryPoint = 'index.js'; + + try { + if (existsSync(join(dirPath, 'package.json'))) { + entryPoint = + JSON.parse(readFileSync(join(dirPath, 'package.json'), { encoding: 'utf8' })).main || + entryPoint; + } + } catch (ignored) { + // ignored + } + + return entryPoint; +} function isDirectory(path) { try { @@ -16,7 +30,7 @@ function isDirectory(path) { return false; } -export default function getDynamicRequirePaths(patterns) { +export default function getDynamicRequireModuleSet(patterns) { const dynamicRequireModuleSet = new Set(); for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) { const isNegated = pattern.startsWith('!'); @@ -28,8 +42,5 @@ export default function getDynamicRequirePaths(patterns) { } } } - const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) => - isDirectory(path) - ); - return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths }; + return dynamicRequireModuleSet; } diff --git a/packages/commonjs/src/generate-exports.js b/packages/commonjs/src/generate-exports.js index f94ae3fe4..7dcb2cdaa 100644 --- a/packages/commonjs/src/generate-exports.js +++ b/packages/commonjs/src/generate-exports.js @@ -30,12 +30,43 @@ export function rewriteExportsAndGetExportsBlock( HELPERS_NAME, exportMode, detectWrappedDefault, - defaultIsModuleExports + defaultIsModuleExports, + usesRequireWrapper, + requireName ) { const exports = []; const exportDeclarations = []; - if (exportMode === 'replace') { + if (usesRequireWrapper) { + // TODO Lukas Extract + if (exportMode === 'replace') { + for (const { left } of moduleExportsAssignments) { + magicString.overwrite(left.start, left.end, exportsName); + } + } else { + // Collect and rewrite module.exports assignments + for (const { left } of moduleExportsAssignments) { + magicString.overwrite(left.start, left.end, `${moduleName}.exports`); + } + // Collect and rewrite named exports + for (const [exportName, { nodes }] of exportsAssignmentsByName) { + for (const node of nodes) { + magicString.overwrite(node.start, node.left.end, `${exportsName}.${exportName}`); + } + } + // Collect and rewrite exports.__esModule assignments + for (const expression of defineCompiledEsmExpressions) { + const moduleExportsExpression = + expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object; + magicString.overwrite( + moduleExportsExpression.start, + moduleExportsExpression.end, + exportsName + ); + } + } + exports.push(`${requireName} as __require`); + } else if (exportMode === 'replace') { getExportsForReplacedModuleExports( magicString, exports, @@ -165,7 +196,8 @@ function getExports( } if (!isRestorableCompiledEsm || defaultIsModuleExports === true) { - exportDeclarations.push(`export default ${exportsName};`); + // TODO Lukas handle ESM importing CommonJS + exports.push(`${exportsName} as default`); } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) { exports.push(`${deconflictedDefaultExportName || exportsName} as default`); } else { diff --git a/packages/commonjs/src/generate-imports.js b/packages/commonjs/src/generate-imports.js index 187572c6a..8f621a260 100644 --- a/packages/commonjs/src/generate-imports.js +++ b/packages/commonjs/src/generate-imports.js @@ -2,7 +2,7 @@ import { dirname, resolve } from 'path'; import { sync as nodeResolveSync } from 'resolve'; -import { EXPORTS_SUFFIX, HELPERS_ID, MODULE_SUFFIX, PROXY_SUFFIX, wrapId } from './helpers'; +import { DYNAMIC_MODULES_ID, EXPORTS_SUFFIX, HELPERS_ID, MODULE_SUFFIX, wrapId } from './helpers'; import { normalizePathSlashes } from './utils'; export function isRequireStatement(node, scope) { @@ -87,53 +87,34 @@ export function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) { } export function getRequireHandlers() { - const requiredSources = []; - const requiredBySource = Object.create(null); - const requiredByNode = new Map(); - const requireExpressionsWithUsedReturnValue = []; - - function addRequireStatement(sourceId, node, scope, usesReturnValue) { - const required = getRequired(sourceId); - requiredByNode.set(node, { scope, required }); - if (usesReturnValue) { - required.nodesUsingRequired.push(node); - requireExpressionsWithUsedReturnValue.push(node); - } - } - - function getRequired(sourceId) { - if (!requiredBySource[sourceId]) { - requiredSources.push(sourceId); - - requiredBySource[sourceId] = { - source: sourceId, - name: null, - nodesUsingRequired: [] - }; - } + const requireExpressions = []; - return requiredBySource[sourceId]; + function addRequireStatement(sourceId, node, scope, usesReturnValue, toBeRemoved) { + requireExpressions.push({ sourceId, node, scope, usesReturnValue, toBeRemoved }); } - function rewriteRequireExpressionsAndGetImportBlock( + async function rewriteRequireExpressionsAndGetImportBlock( magicString, topLevelDeclarations, topLevelRequireDeclarators, reassignedNames, helpersName, - dynamicRegisterSources, + dynamicRequireName, moduleName, exportsName, id, - exportMode + exportMode, + resolveRequireSourcesAndGetMeta, + usesRequireWrapper, + usesRequire ) { - setRemainingImportNamesAndRewriteRequires( - requireExpressionsWithUsedReturnValue, - requiredByNode, - magicString - ); const imports = []; imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`); + if (usesRequire) { + imports.push( + `import { commonjsRequire as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";` + ); + } if (exportMode === 'module') { imports.push( `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify( @@ -145,44 +126,58 @@ export function getRequireHandlers() { `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}` ); } - for (const source of dynamicRegisterSources) { - imports.push(`import ${JSON.stringify(source)};`); - } - for (const source of requiredSources) { - const { name, nodesUsingRequired } = requiredBySource[source]; - imports.push( - `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify( - source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX) - )};` - ); + const requiresBySource = collectSources(requireExpressions); + // TODO Lukas consider extracting stuff + const result = await resolveRequireSourcesAndGetMeta( + usesRequireWrapper ? 'withRequireFunction' : true, + Object.keys(requiresBySource) + ); + let uid = 0; + for (const { source, id: resolveId, isCommonJS } of result) { + const requires = requiresBySource[source]; + let usesRequired = false; + let name; + const hasNameConflict = ({ scope }) => scope.contains(name); + do { + name = `require$$${uid}`; + uid += 1; + } while (requires.some(hasNameConflict)); + + // TODO Lukas extract constant + if (isCommonJS === 'withRequireFunction') { + for (const { node } of requires) { + magicString.overwrite(node.start, node.end, `${name}()`); + } + imports.push(`import { __require as ${name} } from ${JSON.stringify(resolveId)};`); + } else { + for (const { node, usesReturnValue, toBeRemoved } of requires) { + if (usesReturnValue) { + usesRequired = true; + magicString.overwrite(node.start, node.end, name); + } else { + magicString.remove(toBeRemoved.start, toBeRemoved.end); + } + } + imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolveId)};`); + } } return imports.length ? `${imports.join('\n')}\n\n` : ''; } return { addRequireStatement, - requiredSources, rewriteRequireExpressionsAndGetImportBlock }; } -function setRemainingImportNamesAndRewriteRequires( - requireExpressionsWithUsedReturnValue, - requiredByNode, - magicString -) { - let uid = 0; - for (const requireExpression of requireExpressionsWithUsedReturnValue) { - const { required } = requiredByNode.get(requireExpression); - if (!required.name) { - let potentialName; - const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName); - do { - potentialName = `require$$${uid}`; - uid += 1; - } while (required.nodesUsingRequired.some(isUsedName)); - required.name = potentialName; +function collectSources(requireExpressions) { + const requiresBySource = Object.create(null); + for (const { sourceId, node, scope, usesReturnValue, toBeRemoved } of requireExpressions) { + if (!requiresBySource[sourceId]) { + requiresBySource[sourceId] = []; } - magicString.overwrite(requireExpression.start, requireExpression.end, required.name); + const requires = requiresBySource[sourceId]; + requires.push({ node, scope, usesReturnValue, toBeRemoved }); } + return requiresBySource; } diff --git a/packages/commonjs/src/helpers.js b/packages/commonjs/src/helpers.js index 94f6c5719..381761110 100644 --- a/packages/commonjs/src/helpers.js +++ b/packages/commonjs/src/helpers.js @@ -6,17 +6,14 @@ export const PROXY_SUFFIX = '?commonjs-proxy'; export const EXTERNAL_SUFFIX = '?commonjs-external'; export const EXPORTS_SUFFIX = '?commonjs-exports'; export const MODULE_SUFFIX = '?commonjs-module'; +export const ES_IMPORT_SUFFIX = '?es-import'; -export const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register'; -export const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:'; -export const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages'; - +export const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules'; export const HELPERS_ID = '\0commonjsHelpers.js'; // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers. // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled. -// This will no longer be necessary once Rollup switches to ES6 output, likely -// in Rollup 3 +// This could be improved by inspecting Rollup's "generatedCode" option const HELPERS = ` export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; @@ -49,215 +46,6 @@ export function getAugmentedNamespace(n) { } `; -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.');`; - -const HELPER_NON_DYNAMIC = ` -export function commonjsRequire (path) { - ${FAILED_REQUIRE_ERROR} -} -`; - -const getDynamicHelpers = (ignoreDynamicRequires) => ` -export function createModule(modulePath) { - return { - path: modulePath, - exports: {}, - require: function (path, base) { - return commonjsRequire(path, base == null ? modulePath : base); - } - }; -} - -export function commonjsRegister (path, loader) { - DYNAMIC_REQUIRE_LOADERS[path] = loader; -} - -export function commonjsRegisterOrShort (path, to) { - var resolvedPath = commonjsResolveImpl(path, null, true); - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) { - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath]; - } else { - DYNAMIC_REQUIRE_SHORTS[path] = to; - } -} - -var DYNAMIC_REQUIRE_LOADERS = Object.create(null); -var DYNAMIC_REQUIRE_CACHE = Object.create(null); -var DYNAMIC_REQUIRE_SHORTS = Object.create(null); -var DEFAULT_PARENT_MODULE = { - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: [] -}; -var CHECKED_EXTENSIONS = ['', '.js', '.json']; - -function normalize (path) { - path = path.replace(/\\\\/g, '/'); - var parts = path.split('/'); - var slashed = parts[0] === ''; - for (var i = 1; i < parts.length; i++) { - if (parts[i] === '.' || parts[i] === '') { - parts.splice(i--, 1); - } - } - for (var i = 1; i < parts.length; i++) { - if (parts[i] !== '..') continue; - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') { - parts.splice(--i, 2); - i--; - } - } - path = parts.join('/'); - if (slashed && path[0] !== '/') - path = '/' + path; - else if (path.length === 0) - path = '.'; - return path; -} - -function join () { - if (arguments.length === 0) - return '.'; - var joined; - for (var i = 0; i < arguments.length; ++i) { - var arg = arguments[i]; - if (arg.length > 0) { - if (joined === undefined) - joined = arg; - else - joined += '/' + arg; - } - } - if (joined === undefined) - return '.'; - - return joined; -} - -function isPossibleNodeModulesPath (modulePath) { - var c0 = modulePath[0]; - if (c0 === '/' || c0 === '\\\\') return false; - var c1 = modulePath[1], c2 = modulePath[2]; - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) || - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false; - if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) - return false; - return true; -} - -function dirname (path) { - if (path.length === 0) - return '.'; - - var i = path.length - 1; - while (i > 0) { - var c = path.charCodeAt(i); - if ((c === 47 || c === 92) && i !== path.length - 1) - break; - i--; - } - - if (i > 0) - return path.substr(0, i); - - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92) - return path.charAt(0); - - return '.'; -} - -export function commonjsResolveImpl (path, originalModuleDir, testCache) { - var shouldTryNodeModules = isPossibleNodeModulesPath(path); - path = normalize(path); - var relPath; - if (path[0] === '/') { - originalModuleDir = '/'; - } - while (true) { - if (!shouldTryNodeModules) { - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path; - } else if (originalModuleDir) { - relPath = normalize(originalModuleDir + '/node_modules/' + path); - } else { - relPath = normalize(join('node_modules', path)); - } - - if (relPath.endsWith('/..')) { - break; // Travelled too far up, avoid infinite loop - } - - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) { - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex]; - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) { - return resolvedPath; - } - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) { - return resolvedPath; - } - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) { - return resolvedPath; - } - } - if (!shouldTryNodeModules) break; - var nextDir = normalize(originalModuleDir + '/..'); - if (nextDir === originalModuleDir) break; - originalModuleDir = nextDir; - } - return null; -} - -export function commonjsResolve (path, originalModuleDir) { - var resolvedPath = commonjsResolveImpl(path, originalModuleDir); - if (resolvedPath !== null) { - return resolvedPath; - } - return require.resolve(path); -} - -export function commonjsRequire (path, originalModuleDir) { - var resolvedPath = commonjsResolveImpl(path, originalModuleDir, true); - if (resolvedPath !== null) { - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath]; - if (cachedModule) return cachedModule.exports; - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath]; - if (shortTo) { - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo]; - if (cachedModule) - return cachedModule.exports; - resolvedPath = commonjsResolveImpl(shortTo, null, true); - } - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath]; - if (loader) { - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = { - id: resolvedPath, - filename: resolvedPath, - path: dirname(resolvedPath), - exports: {}, - parent: DEFAULT_PARENT_MODULE, - loaded: false, - children: [], - paths: [], - require: function (path, base) { - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base); - } - }; - try { - loader.call(commonjsGlobal, cachedModule, cachedModule.exports); - } catch (error) { - delete DYNAMIC_REQUIRE_CACHE[resolvedPath]; - throw error; - } - cachedModule.loaded = true; - return cachedModule.exports; - }; - } - ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR} -} - -commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE; -commonjsRequire.resolve = commonjsResolve; -`; - -export function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) { - return `${HELPERS}${ - isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC - }`; +export function getHelpersModule() { + return HELPERS; } diff --git a/packages/commonjs/src/index.js b/packages/commonjs/src/index.js index 66e312bb3..af9afcc37 100644 --- a/packages/commonjs/src/index.js +++ b/packages/commonjs/src/index.js @@ -1,4 +1,4 @@ -import { dirname, extname } from 'path'; +import { extname } from 'path'; import { createFilter } from '@rollup/pluginutils'; import getCommonDir from 'commondir'; @@ -6,17 +6,12 @@ import getCommonDir from 'commondir'; import { peerDependencies } from '../package.json'; import analyzeTopLevelStatements from './analyze-top-level-statements'; +import { getDynamicRequireModules } from './dynamic-modules'; +import getDynamicRequireModuleSet from './dynamic-require-paths'; import { - getDynamicPackagesEntryIntro, - getDynamicPackagesModule, - isDynamicModuleImport -} from './dynamic-packages-manager'; -import getDynamicRequirePaths from './dynamic-require-paths'; -import { - DYNAMIC_JSON_PREFIX, - DYNAMIC_PACKAGES_ID, - DYNAMIC_REGISTER_SUFFIX, + DYNAMIC_MODULES_ID, + ES_IMPORT_SUFFIX, EXPORTS_SUFFIX, EXTERNAL_SUFFIX, getHelpersModule, @@ -24,20 +19,15 @@ import { isWrappedId, MODULE_SUFFIX, PROXY_SUFFIX, - unwrapId + unwrapId, + wrapId } from './helpers'; import { hasCjsKeywords } from './parse'; -import { - getDynamicJsonProxy, - getDynamicRequireProxy, - getSpecificHelperProxy, - getStaticRequireProxy, - getUnknownRequireProxy -} from './proxies'; -import getResolveId from './resolve-id'; +import { getStaticRequireProxy, getUnknownRequireProxy } from './proxies'; +import getResolveId, { resolveExtensions } from './resolve-id'; import validateRollupVersion from './rollup-version'; import transformCommonjs from './transform-commonjs'; -import { getName, getVirtualPathForDynamicRequirePath, normalizePathSlashes } from './utils'; +import { capitalize, getName, normalizePathSlashes } from './utils'; export default function commonjs(options = {}) { const extensions = options.extensions || ['.js']; @@ -71,10 +61,9 @@ export default function commonjs(options = {}) { ? defaultIsModuleExportsOption : () => typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto'; + const knownCjsModuleTypes = Object.create(null); - const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths( - options.dynamicRequireTargets - ); + const dynamicRequireModuleSet = getDynamicRequireModuleSet(options.dynamicRequireTargets); const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0; const commonDir = isDynamicRequireModulesEnabled ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd())) @@ -111,12 +100,6 @@ export default function commonjs(options = {}) { const sourceMap = options.sourceMap !== false; function transformAndCheckExports(code, id) { - if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) { - // eslint-disable-next-line no-param-reassign - code = - getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code; - } - const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements( this.parse, code, @@ -136,13 +119,17 @@ export default function commonjs(options = {}) { return { meta: { commonjs: { isCommonJS: false } } }; } - // avoid wrapping as this is a commonjsRegister call - const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX); - if (disableWrap) { - // eslint-disable-next-line no-param-reassign - id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX); - } - + // TODO Lukas + // * test import from ESM -> additional proxy + // * test entry point + // * test interaction with dynamic require targets + // * test circular dependency: We must not use this.load without circularity check -> error in Rollup? + // When we write the imports, we already know that we are commonjs or mixed so we can rely on usesRequireWrapper and write that into a table + const usesRequireWrapper = + !isEsModule && + (dynamicRequireModuleSet.has(normalizePathSlashes(id)) || strictRequireSemanticFilter(id)); + + // TODO Lukas extract helpers return transformCommonjs( this.parse, code, @@ -155,10 +142,58 @@ export default function commonjs(options = {}) { sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, - disableWrap, commonDir, ast, - getDefaultIsModuleExports(id) + getDefaultIsModuleExports(id), + usesRequireWrapper, + // TODO Lukas extract + (isParentCommonJS, sources) => { + knownCjsModuleTypes[id] = isParentCommonJS; + return Promise.all( + sources.map(async (source) => { + // Never analyze or proxy internal modules + if (source.startsWith('\0')) { + return { source, id: source, isCommonJS: false }; + } + const resolved = + (await this.resolve(source, id, { + skipSelf: true, + custom: { + 'node-resolve': { isRequire: true } + } + })) || resolveExtensions(source, id, extensions); + if (!resolved) { + return { source, id: wrapId(source, EXTERNAL_SUFFIX), isCommonJS: false }; + } + if (resolved.external) { + return { source, id: wrapId(resolved.id, EXTERNAL_SUFFIX), isCommonJS: false }; + } + if (resolved.id in knownCjsModuleTypes) { + return { + source, + id: + knownCjsModuleTypes[resolved.id] === true + ? wrapId(resolved.id, PROXY_SUFFIX) + : resolved.id, + isCommonJS: knownCjsModuleTypes[resolved.id] + }; + } + const { + meta: { commonjs: commonjsMeta } + } = await this.load(resolved); + const isCommonJS = commonjsMeta && commonjsMeta.isCommonJS; + return { + source, + id: + // TODO Lukas extract constant + isCommonJS === 'withRequireFunction' + ? resolved.id + : wrapId(resolved.id, PROXY_SUFFIX), + isCommonJS + }; + }) + ); + } ); } @@ -178,40 +213,20 @@ export default function commonjs(options = {}) { load(id) { if (id === HELPERS_ID) { - return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires); - } - - if (id.startsWith(HELPERS_ID)) { - return getSpecificHelperProxy(id); + return getHelpersModule(); } if (isWrappedId(id, MODULE_SUFFIX)) { - const actualId = unwrapId(id, MODULE_SUFFIX); - let name = getName(actualId); - let code; - if (isDynamicRequireModulesEnabled) { - if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) { - name = `${name}_`; - } - code = - `import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` + - `var ${name} = createModule(${JSON.stringify( - getVirtualPathForDynamicRequirePath(dirname(actualId), commonDir) - )});\n` + - `export {${name} as __module}`; - } else { - code = `var ${name} = {exports: {}}; export {${name} as __module}`; - } + const name = getName(unwrapId(id, MODULE_SUFFIX)); return { - code, + code: `var ${name} = {exports: {}}; export {${name} as __module}`, syntheticNamedExports: '__module', meta: { commonjs: { isCommonJS: false } } }; } if (isWrappedId(id, EXPORTS_SUFFIX)) { - const actualId = unwrapId(id, EXPORTS_SUFFIX); - const name = getName(actualId); + const name = getName(unwrapId(id, EXPORTS_SUFFIX)); return { code: `var ${name} = {}; export {${name} as __exports}`, meta: { commonjs: { isCommonJS: false } } @@ -226,23 +241,40 @@ export default function commonjs(options = {}) { ); } - if (id === DYNAMIC_PACKAGES_ID) { - return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir); - } - - if (id.startsWith(DYNAMIC_JSON_PREFIX)) { - return getDynamicJsonProxy(id, commonDir); - } - - if (isDynamicModuleImport(id, dynamicRequireModuleSet)) { - return `export default require(${JSON.stringify(normalizePathSlashes(id))});`; + // TODO Lukas extract + if (isWrappedId(id, ES_IMPORT_SUFFIX)) { + const actualId = unwrapId(id, ES_IMPORT_SUFFIX); + const name = getName(actualId); + const exportsName = `${name}Exports`; + const requireModule = `require${capitalize(name)}`; + // TODO Lukas the ES wrapper might also just forward the exports object + let code = + `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` + + `import { __require as ${requireModule} } from ${JSON.stringify(actualId)};\n` + + `var ${exportsName} = ${requireModule}();\n` + + `export { ${exportsName} as __moduleExports };`; + if (defaultIsModuleExports) { + code += `\nexport { ${exportsName} as default };`; + } else { + code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`; + } + return { + code, + syntheticNamedExports: '__moduleExports', + meta: { commonjs: { isCommonJS: false } } + }; } - if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) { - return getDynamicRequireProxy( - normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)), - commonDir - ); + if (id === DYNAMIC_MODULES_ID) { + return { + code: getDynamicRequireModules( + isDynamicRequireModulesEnabled, + dynamicRequireModuleSet, + commonDir, + ignoreDynamicRequires + ), + meta: { commonjs: { isCommonJS: false } } + }; } if (isWrappedId(id, PROXY_SUFFIX)) { @@ -259,25 +291,14 @@ export default function commonjs(options = {}) { return null; }, - transform(code, rawId) { - let id = rawId; - - if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) { - id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX); - } - + transform(code, id) { const extName = extname(id); - if ( - extName !== '.cjs' && - id !== DYNAMIC_PACKAGES_ID && - !id.startsWith(DYNAMIC_JSON_PREFIX) && - (!filter(id) || !extensions.includes(extName)) - ) { + if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) { return null; } try { - return transformAndCheckExports.call(this, code, rawId); + return transformAndCheckExports.call(this, code, id); } catch (err) { return this.error(err, err.loc); } diff --git a/packages/commonjs/src/proxies.js b/packages/commonjs/src/proxies.js index 125a3d5f3..7fd0b0234 100644 --- a/packages/commonjs/src/proxies.js +++ b/packages/commonjs/src/proxies.js @@ -1,16 +1,9 @@ -import { readFileSync } from 'fs'; - -import { DYNAMIC_JSON_PREFIX, HELPERS_ID } from './helpers'; -import { getName, getVirtualPathForDynamicRequirePath, normalizePathSlashes } from './utils'; - -// e.g. id === "commonjsHelpers?commonjsRegister" -export function getSpecificHelperProxy(id) { - return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`; -} +import { HELPERS_ID } from './helpers'; +import { getName } from './utils'; export function getUnknownRequireProxy(id, requireReturnsDefault) { if (requireReturnsDefault === true || id.endsWith('.json')) { - return `export {default} from ${JSON.stringify(id)};`; + return `export { default } from ${JSON.stringify(id)};`; } const name = getName(id); const exported = @@ -24,23 +17,6 @@ export function getUnknownRequireProxy(id, requireReturnsDefault) { return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`; } -export function getDynamicJsonProxy(id, commonDir) { - const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length)); - return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify( - getVirtualPathForDynamicRequirePath(normalizedPath, commonDir) - )}, function (module, exports) { - module.exports = require(${JSON.stringify(normalizedPath)}); -});`; -} - -export function getDynamicRequireProxy(normalizedPath, commonDir) { - return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify( - getVirtualPathForDynamicRequirePath(normalizedPath, commonDir) - )}, function (module, exports) { - ${readFileSync(normalizedPath, { encoding: 'utf8' })} -});`; -} - export async function getStaticRequireProxy( id, requireReturnsDefault, diff --git a/packages/commonjs/src/resolve-id.js b/packages/commonjs/src/resolve-id.js index 3a3b9a00a..ac59be3a8 100644 --- a/packages/commonjs/src/resolve-id.js +++ b/packages/commonjs/src/resolve-id.js @@ -4,16 +4,14 @@ import { statSync } from 'fs'; import { dirname, resolve, sep } from 'path'; import { - DYNAMIC_JSON_PREFIX, - DYNAMIC_PACKAGES_ID, - DYNAMIC_REGISTER_SUFFIX, + DYNAMIC_MODULES_ID, + ES_IMPORT_SUFFIX, EXPORTS_SUFFIX, EXTERNAL_SUFFIX, HELPERS_ID, isWrappedId, MODULE_SUFFIX, PROXY_SUFFIX, - unwrapId, wrapId } from './helpers'; @@ -28,59 +26,49 @@ function getCandidates(resolved, extensions) { ); } -export default function getResolveId(extensions) { - function resolveExtensions(importee, importer) { - // not our problem - if (importee[0] !== '.' || !importer) return undefined; +export function resolveExtensions(importee, importer, extensions) { + // not our problem + if (importee[0] !== '.' || !importer) return undefined; - const resolved = resolve(dirname(importer), importee); - const candidates = getCandidates(resolved, extensions); + const resolved = resolve(dirname(importer), importee); + const candidates = getCandidates(resolved, extensions); - for (let i = 0; i < candidates.length; i += 1) { - try { - const stats = statSync(candidates[i]); - if (stats.isFile()) return { id: candidates[i] }; - } catch (err) { - /* noop */ - } + for (let i = 0; i < candidates.length; i += 1) { + try { + const stats = statSync(candidates[i]); + if (stats.isFile()) return { id: candidates[i] }; + } catch (err) { + /* noop */ } - - return undefined; } - return function resolveId(importee, rawImporter, resolveOptions) { - if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) { + return undefined; +} + +export default function getResolveId(extensions) { + return async function resolveId(importee, importer, resolveOptions) { + if ( + isWrappedId(importee, MODULE_SUFFIX) || + isWrappedId(importee, EXPORTS_SUFFIX) || + isWrappedId(importee, PROXY_SUFFIX) || + isWrappedId(importee, ES_IMPORT_SUFFIX) || + isWrappedId(importee, EXTERNAL_SUFFIX) + ) { return importee; } - const importer = - rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX) - ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX) - : rawImporter; - // Except for exports, proxies are only importing resolved ids, // no need to resolve again - if (importer && isWrappedId(importer, PROXY_SUFFIX)) { + if ( + importer && + (importer === DYNAMIC_MODULES_ID || + isWrappedId(importer, PROXY_SUFFIX) || + isWrappedId(importer, ES_IMPORT_SUFFIX)) + ) { return importee; } - const isProxyModule = isWrappedId(importee, PROXY_SUFFIX); - let isModuleRegistration = false; - - if (isProxyModule) { - importee = unwrapId(importee, PROXY_SUFFIX); - } else { - isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX); - if (isModuleRegistration) { - importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX); - } - } - - if ( - importee.startsWith(HELPERS_ID) || - importee === DYNAMIC_PACKAGES_ID || - importee.startsWith(DYNAMIC_JSON_PREFIX) - ) { + if (importee.startsWith(HELPERS_ID) || importee === DYNAMIC_MODULES_ID) { return importee; } @@ -88,37 +76,30 @@ export default function getResolveId(extensions) { return null; } - return this.resolve( - importee, - importer, - Object.assign({}, resolveOptions, { - skipSelf: true, - custom: Object.assign({}, resolveOptions.custom, { - 'node-resolve': { isRequire: isProxyModule || isModuleRegistration } - }) - }) - ).then((resolved) => { - if (!resolved) { - resolved = resolveExtensions(importee, importer); - } - if (isProxyModule) { - if (!resolved || resolved.external) { - return { - id: wrapId(resolved ? resolved.id : importee, EXTERNAL_SUFFIX), - external: false - }; + const resolved = + (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) || + resolveExtensions(importee, importer, extensions); + let isCommonJsImporter = false; + if (importer) { + const moduleInfo = this.getModuleInfo(importer); + if (moduleInfo) { + const importerCommonJsMeta = moduleInfo.meta.commonjs; + if ( + importerCommonJsMeta && + (importerCommonJsMeta.isCommonJS || importerCommonJsMeta.isMixedModule) + ) { + isCommonJsImporter = true; } - // This will make sure meta properties in "resolved" are correctly attached to the module - this.load(resolved); - return { - id: wrapId(resolved.id, PROXY_SUFFIX), - external: false - }; } - if (resolved && isModuleRegistration) { - return { id: wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX), external: false }; + } + if (resolved && !isCommonJsImporter) { + const { + meta: { commonjs: commonjsMeta } + } = await this.load(resolved); + if (commonjsMeta && commonjsMeta.isCommonJS === 'withRequireFunction') { + return wrapId(resolved.id, ES_IMPORT_SUFFIX); } - return resolved; - }); + } + return resolved; }; } diff --git a/packages/commonjs/src/transform-commonjs.js b/packages/commonjs/src/transform-commonjs.js index 7698bf9f4..eda4632fc 100644 --- a/packages/commonjs/src/transform-commonjs.js +++ b/packages/commonjs/src/transform-commonjs.js @@ -27,21 +27,14 @@ import { isRequireStatement, isStaticRequireStatement } from './generate-imports'; -import { - DYNAMIC_JSON_PREFIX, - DYNAMIC_REGISTER_SUFFIX, - isWrappedId, - unwrapId, - wrapId -} from './helpers'; import { tryParse } from './parse'; -import { deconflict, getName, getVirtualPathForDynamicRequirePath } from './utils'; +import { capitalize, deconflict, getName, getVirtualPathForDynamicRequirePath } from './utils'; const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/; const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/; -export default function transformCommonjs( +export default async function transformCommonjs( parse, code, id, @@ -53,10 +46,11 @@ export default function transformCommonjs( sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, - disableWrap, commonDir, astCache, - defaultIsModuleExports + defaultIsModuleExports, + usesRequireWrapper, + resolveRequireSourcesAndGetMeta ) { const ast = astCache || tryParse(parse, code, id); const magicString = new MagicString(code); @@ -66,7 +60,6 @@ export default function transformCommonjs( global: false, require: false }; - let usesDynamicRequire = false; const virtualDynamicRequirePath = isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir); let scope = attachScopes(ast, 'scope'); @@ -78,12 +71,11 @@ export default function transformCommonjs( const globals = new Set(); // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯ - const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers'); - const dynamicRegisterSources = new Set(); + const helpersName = deconflict([scope], globals, 'commonjsHelpers'); + const dynamicRequireName = deconflict([scope], globals, 'commonjsRequire'); let hasRemovedRequire = false; - const { addRequireStatement, requiredSources, rewriteRequireExpressionsAndGetImportBlock } = - getRequireHandlers(); + const { addRequireStatement, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers(); // See which names are assigned to. This is necessary to prevent // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`, @@ -196,12 +188,15 @@ export default function transformCommonjs( return; } + // Transform require.resolve if ( node.callee.object && node.callee.object.name === 'require' && node.callee.property.name === 'resolve' && hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet) ) { + // TODO Lukas reimplement + uses.require = true; const requireNode = node.callee.object; magicString.appendLeft( node.end - 1, @@ -209,23 +204,23 @@ export default function transformCommonjs( dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath )}` ); - magicString.overwrite( - requireNode.start, - requireNode.end, - `${HELPERS_NAME}.commonjsRequire`, - { - storeName: true - } - ); + magicString.overwrite(requireNode.start, requireNode.end, dynamicRequireName, { + storeName: true + }); return; } - if (!isStaticRequireStatement(node, scope)) return; - if (!isDynamicRequireModulesEnabled) { - skippedNodes.add(node.callee); + // Ignore call expressions of dynamic requires, the callee will be transformed within Identifier + if (!isStaticRequireStatement(node, scope)) { + return; } + + // Otherwise we do not want to replace "require" with the internal helper + skippedNodes.add(node.callee); + uses.require = true; + + // TODO Lukas can the remaining logic be moved to generate-imports? if (!isIgnoredRequireStatement(node, ignoreRequire)) { - skippedNodes.add(node.callee); const usesReturnValue = parent.type !== 'ExpressionStatement'; let canConvertRequire = true; @@ -240,47 +235,27 @@ export default function transformCommonjs( } } - let sourceId = getRequireStringArg(node); - const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX); - if (isDynamicRegister) { - sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX); - if (sourceId.endsWith('.json')) { - sourceId = DYNAMIC_JSON_PREFIX + sourceId; - } - dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX)); - } else { - if ( - !sourceId.endsWith('.json') && - hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet) - ) { - if (shouldRemoveRequireStatement) { - magicString.overwrite(node.start, node.end, `undefined`); - } else if (canConvertRequire) { - magicString.overwrite( - node.start, - node.end, - `${HELPERS_NAME}.commonjsRequire(${JSON.stringify( - getVirtualPathForDynamicRequirePath(sourceId, commonDir) - )}, ${JSON.stringify( - dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath - )})` - ); - usesDynamicRequire = true; - } - return; + const sourceId = getRequireStringArg(node); + if (shouldRemoveRequireStatement) { + if (usesReturnValue) { + magicString.overwrite(node.start, node.end, `undefined`); + } else { + magicString.remove(parent.start, parent.end); } + return; + } - if (canConvertRequire) { - addRequireStatement(sourceId, node, scope, usesReturnValue); - } + if (canConvertRequire) { + addRequireStatement( + sourceId, + node, + scope, + usesReturnValue, + parent.type === 'ExpressionStatement' ? parent : node + ); } if (usesReturnValue) { - if (shouldRemoveRequireStatement) { - magicString.overwrite(node.start, node.end, `undefined`); - return; - } - if ( parent.type === 'VariableDeclarator' && !scope.parent && @@ -290,14 +265,6 @@ export default function transformCommonjs( // and does not conflict with variables in other places where this is imported topLevelRequireDeclarators.add(parent); } - } else { - // This is a bare import, e.g. `require('foo');` - - if (!canConvertRequire && !shouldRemoveRequireStatement) { - return; - } - - magicString.remove(parent.start, parent.end); } } return; @@ -313,13 +280,15 @@ export default function transformCommonjs( return; case 'Identifier': { const { name } = node; - if (!(isReference(node, parent) && !scope.contains(name))) return; + if (!isReference(node, parent) || scope.contains(name)) return; switch (name) { case 'require': + uses.require = true; if (isNodeRequirePropertyAccess(parent)) { + // TODO Lukas reimplement? if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) { if (parent.property.name === 'cache') { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { + magicString.overwrite(node.start, node.end, dynamicRequireName, { storeName: true }); } @@ -331,22 +300,25 @@ export default function transformCommonjs( if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) { magicString.appendLeft( parent.end - 1, - `,${JSON.stringify( + `, ${JSON.stringify( dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath )}` ); } if (!ignoreDynamicRequires) { if (isShorthandProperty(parent)) { - magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`); + magicString.appendRight(node.end, `: ${dynamicRequireName}`); } else { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { + magicString.overwrite(node.start, node.end, dynamicRequireName, { storeName: true }); } } - usesDynamicRequire = true; return; + // TODO Lukas instead of wrapping, we rewrite everything + // module.exports -> exportsVar, except if it is an assignment, then it is moduleVar.exports + // module -> moduleVar + // only exceptions: Direct assignments to module or exports. Would work with new logic, though. case 'module': case 'exports': shouldWrap = true; @@ -355,7 +327,7 @@ export default function transformCommonjs( case 'global': uses.global = true; if (!ignoreGlobal) { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, { + magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, { storeName: true }); } @@ -372,7 +344,8 @@ export default function transformCommonjs( } case 'MemberExpression': if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { + uses.require = true; + magicString.overwrite(node.start, node.end, dynamicRequireName, { storeName: true }); skippedNodes.add(node.object); @@ -390,7 +363,7 @@ export default function transformCommonjs( if (lexicalDepth === 0) { uses.global = true; if (!ignoreGlobal) { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, { + magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, { storeName: true }); } @@ -432,34 +405,31 @@ export default function transformCommonjs( const nameBase = getName(id); const exportsName = deconflict([...exportsAccessScopes], globals, nameBase); const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`); + const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`); + const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`); const deconflictedExportNames = Object.create(null); for (const [exportName, { scopes }] of exportsAssignmentsByName) { deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName); } // We cannot wrap ES/mixed modules - shouldWrap = - !isEsModule && - !disableWrap && - (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0)); + shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0)); const detectWrappedDefault = shouldWrap && (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0); if ( !( - requiredSources.length || - dynamicRegisterSources.size || + shouldWrap || uses.module || uses.exports || uses.require || - usesDynamicRequire || hasRemovedRequire || topLevelDefineCompiledEsmExpressions.length > 0 ) && (ignoreGlobal || !uses.global) ) { - return { meta: { commonjs: { isCommonJS: false } } }; + return { meta: { commonjs: { isCommonJS: false, isMixedModule: false } } }; } let leadingComment = ''; @@ -481,19 +451,21 @@ export default function transformCommonjs( ? 'exports' : 'module'; - const importBlock = rewriteRequireExpressionsAndGetImportBlock( + const importBlock = await rewriteRequireExpressionsAndGetImportBlock( magicString, topLevelDeclarations, topLevelRequireDeclarators, reassignedNames, - HELPERS_NAME, - dynamicRegisterSources, + helpersName, + dynamicRequireName, moduleName, exportsName, id, - exportMode + exportMode, + resolveRequireSourcesAndGetMeta, + usesRequireWrapper, + uses.require ); - const exportBlock = isEsModule ? '' : rewriteExportsAndGetExportsBlock( @@ -508,16 +480,37 @@ export default function transformCommonjs( topLevelDefineCompiledEsmExpressions, deconflictedExportNames, code, - HELPERS_NAME, + helpersName, exportMode, detectWrappedDefault, - defaultIsModuleExports + defaultIsModuleExports, + usesRequireWrapper, + requireName ); if (shouldWrap) { wrapCode(magicString, uses, moduleName, exportsName); } + if (usesRequireWrapper) { + magicString + .trim() + .indent('\t') + .prepend( + `var ${isRequiredName}; + +function ${requireName} () { +\tif (${isRequiredName}) return ${exportsName}; +\t${isRequiredName} = 1; +` + ).append(` +\treturn ${exportsName}; +}`); + if (exportMode === 'replace') { + magicString.prepend(`var ${exportsName};\n`); + } + } + magicString .trim() .prepend(leadingComment + importBlock) @@ -526,7 +519,13 @@ export default function transformCommonjs( return { code: magicString.toString(), map: sourceMap ? magicString.generateMap() : null, - syntheticNamedExports: isEsModule ? false : '__moduleExports', - meta: { commonjs: { isCommonJS: !isEsModule } } + syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports', + meta: { + // TODO Lukas extract constant + commonjs: { + isCommonJS: !isEsModule && (usesRequireWrapper ? 'withRequireFunction' : true), + isMixedModule: isEsModule + } + } }; } diff --git a/packages/commonjs/src/utils.js b/packages/commonjs/src/utils.js index e226a28fb..b7dc9cda1 100644 --- a/packages/commonjs/src/utils.js +++ b/packages/commonjs/src/utils.js @@ -41,3 +41,7 @@ export const getVirtualPathForDynamicRequirePath = (path, commonDir) => { ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length) : normalizedPath; }; + +export function capitalize(name) { + return name[0].toUpperCase() + name.slice(1); +} diff --git a/packages/commonjs/test/fixtures/form/constant-template-literal/output.js b/packages/commonjs/test/fixtures/form/constant-template-literal/output.js index 96927381c..787983734 100644 --- a/packages/commonjs/test/fixtures/form/constant-template-literal/output.js +++ b/packages/commonjs/test/fixtures/form/constant-template-literal/output.js @@ -1,9 +1,9 @@ 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 "\u0000tape?commonjs-proxy"; +import require$$0 from "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/constant-template-literal/tape.js?commonjs-proxy"; var foo = require$$0; console.log(foo); -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-no-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-no-__esModule/output.js index a180c0faa..24b6fab18 100755 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-no-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-no-__esModule/output.js @@ -4,5 +4,4 @@ import { __exports as input } from "\u0000fixtures/form/defaultIsModuleExports-a var _default = input.default = 2; var named = input.named = 3; -export default input; -export { input as __moduleExports, named }; +export { input as __moduleExports, named, input as default }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-__esModule/output.js index 59c3241c0..c0cde8ae9 100755 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-__esModule/output.js @@ -4,5 +4,4 @@ import { __exports as input } from "\u0000fixtures/form/defaultIsModuleExports-f var _default = input.default = 2; var named = input.named = 3; -export default input; -export { input as __moduleExports, named }; +export { input as __moduleExports, named, input as default }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-default/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-default/output.js index 7376b2e0f..fd8c2d238 100755 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-default/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-default/output.js @@ -3,5 +3,4 @@ import { __exports as input } from "\u0000fixtures/form/defaultIsModuleExports-f var named = input.named = 3; -export default input; -export { input as __moduleExports, named }; +export { input as __moduleExports, named, input as default }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-__esModule/output.js index 481eb01bc..48a71f980 100755 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-__esModule/output.js @@ -5,5 +5,4 @@ input.__esModule = true; var _default = input.default = 2; var named = input.named = 3; -export default input; -export { input as __moduleExports, named }; +export { input as __moduleExports, named, input as default }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-no-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-no-__esModule/output.js index 1dcb6d233..512b2330e 100755 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-no-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-no-__esModule/output.js @@ -4,5 +4,4 @@ import { __exports as input } from "\u0000fixtures/form/defaultIsModuleExports-t var _default = input.default = 2; var named = input.named = 3; -export default input; -export { input as __moduleExports, named }; +export { input as __moduleExports, named, input as default }; diff --git a/packages/commonjs/test/fixtures/form/dynamic-template-literal/output.js b/packages/commonjs/test/fixtures/form/dynamic-template-literal/output.js index dda7d8f08..2b301a21b 100644 --- a/packages/commonjs/test/fixtures/form/dynamic-template-literal/output.js +++ b/packages/commonjs/test/fixtures/form/dynamic-template-literal/output.js @@ -1,9 +1,9 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; +import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules"; import { __exports as input } from "\u0000fixtures/form/dynamic-template-literal/input.js?commonjs-exports" var pe = 'pe'; -var foo = commonjsHelpers.commonjsRequire(`ta${pe}`); +var foo = commonjsRequire(`ta${pe}`); console.log(foo); -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/ignore-ids-function/output.js b/packages/commonjs/test/fixtures/form/ignore-ids-function/output.js index 496cc2ba8..5fc418cd4 100644 --- a/packages/commonjs/test/fixtures/form/ignore-ids-function/output.js +++ b/packages/commonjs/test/fixtures/form/ignore-ids-function/output.js @@ -1,9 +1,9 @@ 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 "\u0000bar?commonjs-proxy"; +import require$$0 from "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/ignore-ids-function/bar.js?commonjs-proxy"; var foo = require( 'foo' ); var bar = require$$0; -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/ignore-ids/output.js b/packages/commonjs/test/fixtures/form/ignore-ids/output.js index 0df09cce8..83b9d1e9f 100644 --- a/packages/commonjs/test/fixtures/form/ignore-ids/output.js +++ b/packages/commonjs/test/fixtures/form/ignore-ids/output.js @@ -1,9 +1,9 @@ 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 "\u0000bar?commonjs-proxy"; +import require$$0 from "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/ignore-ids/bar.js?commonjs-proxy"; var foo = require( 'foo' ); var bar = require$$0; -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/multi-entry-module-exports/output1.js b/packages/commonjs/test/fixtures/form/multi-entry-module-exports/output1.js index 060d12a53..cd261710a 100644 --- a/packages/commonjs/test/fixtures/form/multi-entry-module-exports/output1.js +++ b/packages/commonjs/test/fixtures/form/multi-entry-module-exports/output1.js @@ -1,5 +1,6 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; -import require$$0 from "\u0000./input2.js?commonjs-proxy"; +import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules"; +import require$$0 from "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/multi-entry-module-exports/input2.js?commonjs-proxy"; const t2 = require$$0; diff --git a/packages/commonjs/test/fixtures/form/multiple-var-declarations-b/output.js b/packages/commonjs/test/fixtures/form/multiple-var-declarations-b/output.js index 7fc075484..0186bc7eb 100644 --- a/packages/commonjs/test/fixtures/form/multiple-var-declarations-b/output.js +++ b/packages/commonjs/test/fixtures/form/multiple-var-declarations-b/output.js @@ -1,11 +1,11 @@ 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 "\u0000./a?commonjs-proxy"; +import require$$0 from "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/multiple-var-declarations-b/a.js?commonjs-proxy"; var a = require$$0 , b = 42; console.log( a, b ); -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/multiple-var-declarations-c/output.js b/packages/commonjs/test/fixtures/form/multiple-var-declarations-c/output.js index e8542c6c5..4101b47e8 100644 --- a/packages/commonjs/test/fixtures/form/multiple-var-declarations-c/output.js +++ b/packages/commonjs/test/fixtures/form/multiple-var-declarations-c/output.js @@ -1,6 +1,7 @@ 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 "\u0000./b?commonjs-proxy"; +import require$$0 from "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/multiple-var-declarations-c/b.js?commonjs-proxy"; var a = 'a' , b = require$$0 @@ -8,5 +9,4 @@ var a = 'a' console.log( a, b, c ); -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/multiple-var-declarations/output.js b/packages/commonjs/test/fixtures/form/multiple-var-declarations/output.js index a7de41c4b..60c5118b9 100644 --- a/packages/commonjs/test/fixtures/form/multiple-var-declarations/output.js +++ b/packages/commonjs/test/fixtures/form/multiple-var-declarations/output.js @@ -1,12 +1,12 @@ 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 "\u0000./a?commonjs-proxy"; -import require$$1 from "\u0000./b?commonjs-proxy"; +import require$$0 from "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/multiple-var-declarations/a.js?commonjs-proxy"; +import require$$1 from "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/multiple-var-declarations/b.js?commonjs-proxy"; var a = require$$0() , b = require$$1; console.log( a, b ); -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/no-exports-entry/output.js b/packages/commonjs/test/fixtures/form/no-exports-entry/output.js index 45a5c8495..3e83089b2 100644 --- a/packages/commonjs/test/fixtures/form/no-exports-entry/output.js +++ b/packages/commonjs/test/fixtures/form/no-exports-entry/output.js @@ -1,6 +1,7 @@ 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 "\u0000./dummy?commonjs-proxy"; +import require$$0 from "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/no-exports-entry/dummy.js?commonjs-proxy"; var dummy = require$$0; @@ -10,5 +11,4 @@ var foo = function () { var input = 42; -export default input_1; -export { input_1 as __moduleExports }; +export { input_1 as __moduleExports, input_1 as default }; diff --git a/packages/commonjs/test/fixtures/form/node-require-methods/output.js b/packages/commonjs/test/fixtures/form/node-require-methods/output.js index 1192a708d..b1ceb2c2a 100644 --- a/packages/commonjs/test/fixtures/form/node-require-methods/output.js +++ b/packages/commonjs/test/fixtures/form/node-require-methods/output.js @@ -1,9 +1,9 @@ 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) { return require.resolve(someFile); }; -export default input; -export { input as __moduleExports, getFilePath }; +export { input as __moduleExports, getFilePath, input as default }; diff --git a/packages/commonjs/test/fixtures/form/optimised-named-export-conflicts/output.js b/packages/commonjs/test/fixtures/form/optimised-named-export-conflicts/output.js index 2a8ab72b4..a91b08d2d 100644 --- a/packages/commonjs/test/fixtures/form/optimised-named-export-conflicts/output.js +++ b/packages/commonjs/test/fixtures/form/optimised-named-export-conflicts/output.js @@ -7,5 +7,4 @@ var bar = 2; var foo_1 = input.foo = 'a'; var bar_1 = input.bar = 'b'; -export default input; -export { input as __moduleExports, foo_1 as foo, bar_1 as bar }; +export { input as __moduleExports, foo_1 as foo, bar_1 as bar, input as default }; diff --git a/packages/commonjs/test/fixtures/form/optimised-named-export/output.js b/packages/commonjs/test/fixtures/form/optimised-named-export/output.js index 4f5d1feca..e5ca89b12 100644 --- a/packages/commonjs/test/fixtures/form/optimised-named-export/output.js +++ b/packages/commonjs/test/fixtures/form/optimised-named-export/output.js @@ -4,5 +4,4 @@ import { __exports as input } from "\u0000fixtures/form/optimised-named-export/i var foo = input.foo = 'a'; var bar = input.bar = 'b'; -export default input; -export { input as __moduleExports, foo, bar }; +export { input as __moduleExports, foo, bar, input as default }; diff --git a/packages/commonjs/test/fixtures/form/require-collision/output.js b/packages/commonjs/test/fixtures/form/require-collision/output.js index 401ca324b..22eb3c645 100644 --- a/packages/commonjs/test/fixtures/form/require-collision/output.js +++ b/packages/commonjs/test/fixtures/form/require-collision/output.js @@ -1,6 +1,7 @@ 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 "\u0000foo?commonjs-proxy"; +import require$$1 from "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/require-collision/foo.js?commonjs-proxy"; (function() { var foo = require$$1; @@ -8,5 +9,4 @@ import require$$1 from "\u0000foo?commonjs-proxy"; console.log(foo); })(); -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/try-catch-remove/output.js b/packages/commonjs/test/fixtures/form/try-catch-remove/output.js index 1b73e073c..e18f11df0 100644 --- a/packages/commonjs/test/fixtures/form/try-catch-remove/output.js +++ b/packages/commonjs/test/fixtures/form/try-catch-remove/output.js @@ -1,5 +1,6 @@ /* eslint-disable global-require */ import * as commonjsHelpers from "_commonjsHelpers.js"; +import { commonjsRequire as commonjsRequire } from "_commonjs-dynamic-modules"; import { __exports as input } from "\u0000fixtures/form/try-catch-remove/input.js?commonjs-exports" try { @@ -8,5 +9,4 @@ try { /* ignore */ } -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/unambiguous-with-default-export/output.js b/packages/commonjs/test/fixtures/form/unambiguous-with-default-export/output.js index 00f1c462a..6c0116507 100644 --- a/packages/commonjs/test/fixtures/form/unambiguous-with-default-export/output.js +++ b/packages/commonjs/test/fixtures/form/unambiguous-with-default-export/output.js @@ -1,5 +1,6 @@ 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 "\u0000./foo.js?commonjs-proxy"; +import "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/unambiguous-with-default-export/foo.js?commonjs-proxy"; export default {}; diff --git a/packages/commonjs/test/fixtures/form/unambiguous-with-import/output.js b/packages/commonjs/test/fixtures/form/unambiguous-with-import/output.js index b045cc0bd..b1dd5178e 100644 --- a/packages/commonjs/test/fixtures/form/unambiguous-with-import/output.js +++ b/packages/commonjs/test/fixtures/form/unambiguous-with-import/output.js @@ -1,5 +1,6 @@ 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 "\u0000./foo.js?commonjs-proxy"; +import "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/unambiguous-with-import/foo.js?commonjs-proxy"; import './bar.js'; diff --git a/packages/commonjs/test/fixtures/form/unambiguous-with-named-export/output.js b/packages/commonjs/test/fixtures/form/unambiguous-with-named-export/output.js index bfa3f4e51..d7428f35e 100644 --- a/packages/commonjs/test/fixtures/form/unambiguous-with-named-export/output.js +++ b/packages/commonjs/test/fixtures/form/unambiguous-with-named-export/output.js @@ -1,5 +1,6 @@ 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 "\u0000./foo.js?commonjs-proxy"; +import "\u0000/Users/lukastaegert/Github/rollup-plugins/packages/commonjs/test/fixtures/form/unambiguous-with-named-export/foo.js?commonjs-proxy"; export {}; diff --git a/packages/commonjs/test/fixtures/function/cjs-extension/_config.js b/packages/commonjs/test/fixtures/function/cjs-extension/_config.js new file mode 100644 index 000000000..1edda6c48 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/cjs-extension/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'imports .cjs file extension by default' +}; diff --git a/packages/commonjs/test/fixtures/samples/cjs-extension/export.cjs b/packages/commonjs/test/fixtures/function/cjs-extension/export.cjs similarity index 100% rename from packages/commonjs/test/fixtures/samples/cjs-extension/export.cjs rename to packages/commonjs/test/fixtures/function/cjs-extension/export.cjs diff --git a/packages/commonjs/test/fixtures/samples/cjs-extension/main.js b/packages/commonjs/test/fixtures/function/cjs-extension/main.js similarity index 69% rename from packages/commonjs/test/fixtures/samples/cjs-extension/main.js rename to packages/commonjs/test/fixtures/function/cjs-extension/main.js index b76e19952..fc1029fd7 100644 --- a/packages/commonjs/test/fixtures/samples/cjs-extension/main.js +++ b/packages/commonjs/test/fixtures/function/cjs-extension/main.js @@ -1,3 +1,3 @@ const { test } = require('./export.cjs'); -console.log(test); +t.is(test, 42); diff --git a/packages/commonjs/test/fixtures/function/custom-options/_config.js b/packages/commonjs/test/fixtures/function/custom-options/_config.js index a54562867..522f2c94a 100644 --- a/packages/commonjs/test/fixtures/function/custom-options/_config.js +++ b/packages/commonjs/test/fixtures/function/custom-options/_config.js @@ -22,10 +22,10 @@ module.exports = { 'other.js', 'main.js', // This is the important one - { custom: { test: 42, 'node-resolve': { isRequire: false } }, isEntry: true } + { custom: { test: 42 }, isEntry: true } ], ['main.js', void 0, { custom: {}, isEntry: true }], - ['main.js', void 0, { custom: { 'node-resolve': { isRequire: false } }, isEntry: true }] + ['main.js', void 0, { custom: {}, isEntry: true }] ]); }, resolveId(source, importer, options) { diff --git a/packages/commonjs/test/fixtures/function/custom-options/main.js b/packages/commonjs/test/fixtures/function/custom-options/main.js index c0b933d7b..36aa4b64f 100644 --- a/packages/commonjs/test/fixtures/function/custom-options/main.js +++ b/packages/commonjs/test/fixtures/function/custom-options/main.js @@ -1 +1 @@ -console.log('main'); +t.is('main', 'main'); diff --git a/packages/commonjs/test/fixtures/function/custom-options/other.js b/packages/commonjs/test/fixtures/function/custom-options/other.js index 8bbad80dc..edd7566fb 100644 --- a/packages/commonjs/test/fixtures/function/custom-options/other.js +++ b/packages/commonjs/test/fixtures/function/custom-options/other.js @@ -1 +1 @@ -console.log('other'); +throw new Error('Other should not be executed'); diff --git a/packages/commonjs/test/fixtures/function/dynamic-module-require/_config.js b/packages/commonjs/test/fixtures/function/dynamic-module-require/_config.js index 0693ea19d..be6712858 100755 --- a/packages/commonjs/test/fixtures/function/dynamic-module-require/_config.js +++ b/packages/commonjs/test/fixtures/function/dynamic-module-require/_config.js @@ -1,4 +1,6 @@ module.exports = { + // TODO Lukas think about a way to re-implement + skip: true, description: 'supports dynamic require', pluginOptions: { dynamicRequireTargets: ['fixtures/function/dynamic-module-require/submodule.js'] diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/_config.js index 6085df3dc..c72a299c4 100755 --- a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/_config.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/_config.js @@ -1,6 +1,8 @@ const { nodeResolve } = require('@rollup/plugin-node-resolve'); module.exports = { + // TODO Lukas re-enable cache-handling in some way + skip: true, description: 'accesses commonjsRequire.cache', options: { plugins: [nodeResolve()] diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/_config.js new file mode 100644 index 000000000..886b59564 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/_config.js @@ -0,0 +1,21 @@ +const path = require('path'); + +module.exports = { + description: 'handles dynamic requires when entry is from a custom loader', + options: { + plugins: [ + { + load(id) { + if (id === path.resolve('fixtures/function/dynamic-require-different-loader/main.js')) { + return 'import submodule1 from "./submodule1"; export default submodule1();'; + } + return null; + } + } + ] + }, + pluginOptions: { + dynamicRequireTargets: ['fixtures/function/dynamic-require-different-loader/submodule2.js'], + transformMixedEsModules: true + } +}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/main.js b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/main.js new file mode 100755 index 000000000..4b24999ae --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/main.js @@ -0,0 +1 @@ +throw new Error('Should be replaced by a custom loader'); diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/submodule1.js b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/submodule1.js similarity index 100% rename from packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/submodule1.js rename to packages/commonjs/test/fixtures/function/dynamic-require-different-loader/submodule1.js diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/submodule2.js b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/submodule2.js similarity index 100% rename from packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/submodule2.js rename to packages/commonjs/test/fixtures/function/dynamic-require-different-loader/submodule2.js diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/_config.js new file mode 100755 index 000000000..df33c9e84 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/_config.js @@ -0,0 +1,7 @@ +module.exports = { + description: 'supports strict require semantic in mixed modules', + pluginOptions: { + strictRequireSemantic: true, + transformMixedEsModules: true + } +}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/importer.js b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/importer.js new file mode 100755 index 000000000..ab6eb9fa2 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/importer.js @@ -0,0 +1,7 @@ +t.is(global.hasSubmoduleRun, undefined, 'before require'); + +// eslint-disable-next-line global-require +export default require('./submodule.js'); + +t.is(global.hasSubmoduleRun, true, 'after require'); +delete global.hasSubmoduleRun; diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/main.js b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/main.js similarity index 50% rename from packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/main.js rename to packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/main.js index 523e6c2dc..a7add1fba 100755 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/main.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/main.js @@ -1,5 +1,3 @@ -/* eslint-disable import/no-dynamic-require, global-require */ - import result from './importer.js'; t.is(result, 'submodule'); diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/submodule.js b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/submodule.js new file mode 100755 index 000000000..15eb5a9b1 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/submodule.js @@ -0,0 +1,2 @@ +global.hasSubmoduleRun = true; +module.exports = 'submodule'; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-root-circular/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-root-circular/_config.js index c426b3756..15ca843d9 100755 --- a/packages/commonjs/test/fixtures/function/dynamic-require-root-circular/_config.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-root-circular/_config.js @@ -1,7 +1,7 @@ const { nodeResolve } = require('@rollup/plugin-node-resolve'); module.exports = { - description: 'resolves circular references through indirect access (../ to module\'s root)', + description: "resolves circular references through indirect access (../ to module's root)", options: { plugins: [nodeResolve()] }, diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/_config.js index 0713326f6..013229479 100755 --- a/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/_config.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/_config.js @@ -1,9 +1,6 @@ const { nodeResolve } = require('@rollup/plugin-node-resolve'); module.exports = { - // TODO This test is broken because for dynamic require targets with dependencies, the dependencies are hoisted - // above the dynamic register calls at the moment - skip: true, description: 'resolves imports of node_modules module with halfway / subfolder access', options: { plugins: [nodeResolve()] diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/main.js b/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/main.js index cee139817..111bd1688 100755 --- a/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/main.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/main.js @@ -4,13 +4,13 @@ function takeModule(name) { return require(name); } -t.is(takeModule('.'), 'same-directory'); -t.is(takeModule('./'), 'same-directory'); -t.is(takeModule('.//'), 'same-directory'); +t.is(takeModule('.'), 'same-directory', '.'); +t.is(takeModule('./'), 'same-directory', './'); +t.is(takeModule('.//'), 'same-directory', './/'); -t.is(takeModule('./sub'), 'sub'); +t.is(takeModule('./sub'), 'sub', './sub'); -t.is(takeModule('custom-module'), 'custom-module + sub'); +t.is(takeModule('custom-module'), 'custom-module + sub', 'custom-module'); t.deepEqual(require('./sub/sub'), { parent: 'same-directory', customModule: 'custom-module + sub' diff --git a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/_config.js b/packages/commonjs/test/fixtures/function/no-default-export-live-binding/_config.js deleted file mode 100644 index 13fadfa24..000000000 --- a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/_config.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = { - description: 'there should not be a live-binding for the default export' -}; diff --git a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep1.js b/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep1.js deleted file mode 100644 index ec206b365..000000000 --- a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep1.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = { - foo: 'foo', - update: () => (module.exports = { foo: 'bar' }) -}; diff --git a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep2.js b/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep2.js deleted file mode 100644 index f3b624c2e..000000000 --- a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep2.js +++ /dev/null @@ -1,2 +0,0 @@ -module.exports.foo = 'foo'; -module.exports.update = () => (module.exports = { foo: 'bar' }); diff --git a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep3.js b/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep3.js deleted file mode 100644 index 2254de7eb..000000000 --- a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep3.js +++ /dev/null @@ -1,2 +0,0 @@ -exports.foo = 'foo'; -module.exports.update = () => (module.exports = { foo: 'bar' }); diff --git a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/main.js b/packages/commonjs/test/fixtures/function/no-default-export-live-binding/main.js deleted file mode 100644 index 75edbb4f4..000000000 --- a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/main.js +++ /dev/null @@ -1,15 +0,0 @@ -import dep1 from './dep1.js'; -import dep2 from './dep2.js'; -import dep3 from './dep3.js'; - -t.is(dep1.foo, 'foo', 'dep1'); -dep1.update(); -t.is(dep1.foo, 'foo', 'dep1 updated'); - -t.is(dep2.foo, 'foo', 'dep2'); -dep2.update(); -t.is(dep2.foo, 'foo', 'dep2 updated'); - -t.is(dep3.foo, 'foo', 'dep3'); -dep3.update(); -t.is(dep3.foo, 'foo', 'dep3 updated'); diff --git a/packages/commonjs/test/fixtures/function/reassign-module/main.js b/packages/commonjs/test/fixtures/function/reassign-module/main.js index 1e30b5021..17bbecf93 100644 --- a/packages/commonjs/test/fixtures/function/reassign-module/main.js +++ b/packages/commonjs/test/fixtures/function/reassign-module/main.js @@ -3,7 +3,7 @@ const property = require('./property'); const arrayPattern = require('./array-pattern.js'); const assignmentPattern = require('./assignment-pattern.js'); -t.deepEqual(identifier, {}); -t.deepEqual(property, {}); -t.deepEqual(arrayPattern, {}); -t.deepEqual(assignmentPattern, {}); +t.deepEqual(identifier, {}, 'identifier'); +t.deepEqual(property, {}, 'property'); +t.deepEqual(arrayPattern, {}, 'arrayPattern'); +t.deepEqual(assignmentPattern, {}, 'assignmentPattern'); diff --git a/packages/commonjs/test/fixtures/function/shorthand-require/_config.js b/packages/commonjs/test/fixtures/function/shorthand-require/_config.js new file mode 100755 index 000000000..00d2b9db7 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/shorthand-require/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'correctly replaces shorthand `require` property in object' +}; diff --git a/packages/commonjs/test/fixtures/samples/shorthand-require/main.js b/packages/commonjs/test/fixtures/function/shorthand-require/main.js similarity index 100% rename from packages/commonjs/test/fixtures/samples/shorthand-require/main.js rename to packages/commonjs/test/fixtures/function/shorthand-require/main.js diff --git a/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/_config.js b/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/_config.js new file mode 100644 index 000000000..30b61d0c5 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/_config.js @@ -0,0 +1,6 @@ +module.exports = { + description: 'supports using function wrappers for modules', + pluginOptions: { + strictRequireSemantic: ['fixtures/function/strict-require-semantic-exportmode-exports/*E*.js'] + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/assignExports.js b/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/assignExports.js new file mode 100644 index 000000000..5e58a22e5 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/assignExports.js @@ -0,0 +1,2 @@ +exports.foo = 'foo'; +global.hasAssignExportsRun = true; diff --git a/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/compiledEsm.js b/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/compiledEsm.js new file mode 100644 index 000000000..b011461c8 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/compiledEsm.js @@ -0,0 +1,4 @@ +exports.__esModule = true; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.foo = 'foo'; +global.hasCompiledEsmRun = true; diff --git a/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/main.js b/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/main.js new file mode 100644 index 000000000..90fca158f --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/main.js @@ -0,0 +1,17 @@ +t.is(global.hasAssignExportsRun, undefined, 'before require'); +t.is(require('./assignExports.js').foo, 'foo'); + +t.is(global.hasAssignExportsRun, true, 'after require'); +delete global.hasAssignExportsRun; + +t.is(global.hasReassignModuleExportsRun, undefined, 'before require'); +t.is(require('./reassignModuleExports.js').foo, 'foo'); + +t.is(global.hasReassignModuleExportsRun, true, 'after require'); +delete global.hasReassignModuleExportsRun; + +t.is(global.hasCompiledEsmRun, undefined, 'before require'); +t.is(require('./compiledEsm.js').foo, 'foo'); + +t.is(global.hasCompiledEsmRun, true, 'after require'); +delete global.hasCompiledEsmRun; diff --git a/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/reassignModuleExports.js b/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/reassignModuleExports.js new file mode 100644 index 000000000..d988c04a8 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-require-semantic-exportmode-exports/reassignModuleExports.js @@ -0,0 +1,3 @@ +module.exports = { bar: 'bar' }; +module.exports.foo = 'foo'; +global.hasReassignModuleExportsRun = true; diff --git a/packages/commonjs/test/fixtures/function/typeof-module-require/foo.js b/packages/commonjs/test/fixtures/function/typeof-module-require/foo.js index 8ddba70a6..8efe5218f 100644 --- a/packages/commonjs/test/fixtures/function/typeof-module-require/foo.js +++ b/packages/commonjs/test/fixtures/function/typeof-module-require/foo.js @@ -1,5 +1,5 @@ if (typeof module.require === 'function' && module.require) { - module.exports = 1; + module.exports = 'require detected'; } else { - module.exports = 2; + module.exports = 'could not detect require'; } diff --git a/packages/commonjs/test/fixtures/function/typeof-module-require/main.js b/packages/commonjs/test/fixtures/function/typeof-module-require/main.js index 6f32f015a..57de0e64f 100644 --- a/packages/commonjs/test/fixtures/function/typeof-module-require/main.js +++ b/packages/commonjs/test/fixtures/function/typeof-module-require/main.js @@ -1,3 +1,3 @@ import foo from './foo.js'; -t.is(foo, 1); +t.is(foo, 'require detected'); diff --git a/packages/commonjs/test/fixtures/function/unresolved-dependencies/_config.js b/packages/commonjs/test/fixtures/function/unresolved-dependencies/_config.js index a7daf279e..72b184cf6 100644 --- a/packages/commonjs/test/fixtures/function/unresolved-dependencies/_config.js +++ b/packages/commonjs/test/fixtures/function/unresolved-dependencies/_config.js @@ -11,9 +11,12 @@ module.exports = { plugins: [ { buildEnd() { - assert.strictEqual(warnings.length, 1); - assert.strictEqual(warnings[0].code, 'UNRESOLVED_IMPORT'); - assert.strictEqual(warnings[0].source, 'path'); + assert.deepStrictEqual( + warnings.map(({ code, source }) => { + return { code, source }; + }), + [{ code: 'UNRESOLVED_IMPORT', source: 'path' }] + ); } } ] diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/main.js b/packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/main.js deleted file mode 100755 index 8adb18ef2..000000000 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/main.js +++ /dev/null @@ -1 +0,0 @@ -// will be actually be loaded by the custom loader diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/main.js b/packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/main.js deleted file mode 100644 index d064297ec..000000000 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/main.js +++ /dev/null @@ -1 +0,0 @@ -require('./submodule'); diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/submodule.js b/packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/submodule.js deleted file mode 100644 index 837892314..000000000 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/submodule.js +++ /dev/null @@ -1,3 +0,0 @@ -Object.defineProperty(exports, '__esModule', { value: true }); - -module.exports = 'submodule'; diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/importer.js b/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/importer.js deleted file mode 100755 index 6acaa9d43..000000000 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/importer.js +++ /dev/null @@ -1,2 +0,0 @@ -// eslint-disable-next-line global-require -export default require('./submodule.js'); diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/submodule.js b/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/submodule.js deleted file mode 100755 index c285d34bc..000000000 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/submodule.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'submodule'; diff --git a/packages/commonjs/test/form.js b/packages/commonjs/test/form.js index f9de9cb65..d551cc43b 100644 --- a/packages/commonjs/test/form.js +++ b/packages/commonjs/test/form.js @@ -1,6 +1,7 @@ /* eslint-disable global-require, import/no-dynamic-require, no-console */ import * as fs from 'fs'; +import * as path from 'path'; import * as acorn from 'acorn'; import test from 'ava'; @@ -15,7 +16,12 @@ const transformContext = { ecmaVersion: 9, sourceType: 'module', ...options - }) + }), + resolve: (source, importer) => + Promise.resolve({ + id: `${path.resolve(path.dirname(importer), source)}${path.extname(source) ? '' : '.js'}` + }), + load: ({ id }) => Promise.resolve({ id, meta: {} }) }; fs.readdirSync('./fixtures/form').forEach((dir) => { @@ -37,55 +43,58 @@ fs.readdirSync('./fixtures/form').forEach((dir) => { inputEntries.push(['output', `fixtures/form/${dir}/input.js`]); } - (config.solo ? test.only : test)(dir, async (t) => { - for (const [outputName, id] of inputEntries) { - const { transform } = commonjs(config.options); - - transformContext.getModuleInfo = (moduleId) => { - return { - isEntry: config.entry && moduleId === id, - importers: - config.importers && config.importers[outputName] - ? config.importers[outputName].map((x) => `fixtures/form/${dir}/${x}`) - : [] + (config.solo ? test.only : test)(dir, (t) => + Promise.all( + inputEntries.map(async ([outputName, id]) => { + const { transform } = commonjs(config.options); + + transformContext.getModuleInfo = (moduleId) => { + return { + isEntry: config.entry && moduleId === id, + importers: + config.importers && config.importers[outputName] + ? config.importers[outputName].map((x) => `fixtures/form/${dir}/${x}`) + : [] + }; }; - }; - transformContext.error = (base, props) => { - let error = base; - if (!(base instanceof Error)) error = Object.assign(new Error(base.message), base); - if (props) Object.assign(error, props); - throw error; - }; - - const input = fs.readFileSync(id, 'utf-8'); - - let outputFile = `fixtures/form/${dir}/${outputName}`; - if (fs.existsSync(`${outputFile}.${process.platform}.js`)) { - outputFile += `.${process.platform}.js`; - } else { - outputFile += '.js'; - } - - const expected = fs.readFileSync(outputFile, 'utf-8').trim(); - const transformed = transform.call(transformContext, input, id); - const actual = (transformed ? transformed.code : input).trim().replace(/\0/g, '_'); - - // uncomment to update snapshots - // fs.writeFileSync(outputFile, `${actual}\n`); - - // trim whitespace from line endings, - // this will benefit issues like `form/try-catch-remove` where whitespace is left in the line, - // and testing on windows (\r\n) - t.is( - actual - .split('\n') - .map((x) => x.trimEnd()) - .join('\n'), - expected - .split('\n') - .map((x) => x.trimEnd()) - .join('\n') - ); - } - }); + transformContext.error = (base, props) => { + let error = base; + if (!(base instanceof Error)) error = Object.assign(new Error(base.message), base); + if (props) Object.assign(error, props); + throw error; + }; + + const input = fs.readFileSync(id, 'utf-8'); + + let outputFile = `fixtures/form/${dir}/${outputName}`; + if (fs.existsSync(`${outputFile}.${process.platform}.js`)) { + outputFile += `.${process.platform}.js`; + } else { + outputFile += '.js'; + } + + const expected = fs.readFileSync(outputFile, 'utf-8').trim(); + // eslint-disable-next-line no-await-in-loop + const transformed = await transform.call(transformContext, input, id); + const actual = (transformed ? transformed.code : input).trim().replace(/\0/g, '_'); + + // uncomment to update snapshots + // fs.writeFileSync(outputFile, `${actual}\n`); + + // trim whitespace from line endings, + // this will benefit issues like `form/try-catch-remove` where whitespace is left in the line, + // and testing on windows (\r\n) + t.is( + actual + .split('\n') + .map((x) => x.trimEnd()) + .join('\n'), + expected + .split('\n') + .map((x) => x.trimEnd()) + .join('\n') + ); + }) + ) + ); }); diff --git a/packages/commonjs/test/snapshots/function.js.md b/packages/commonjs/test/snapshots/function.js.md index 39078a541..48dcc52e9 100644 --- a/packages/commonjs/test/snapshots/function.js.md +++ b/packages/commonjs/test/snapshots/function.js.md @@ -11,16 +11,14 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var foo$2 = {exports: {}};␊ + var foo$1 = {exports: {}};␊ ␊ const foo = {};␊ ␊ - foo$2.exports = foo;␊ - foo$2.exports.bar = 1;␊ - ␊ - var foo$1 = foo$2.exports;␊ + foo$1.exports = foo;␊ + foo$1.exports.bar = 1;␊ ␊ - t.is(foo$1.bar, 1);␊ + t.is(foo$1.exports.bar, 1);␊ `, } @@ -31,19 +29,17 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var document$2 = {exports: {}};␊ + var document$1 = {exports: {}};␊ ␊ /* eslint-disable */␊ ␊ if (typeof document !== 'undefined') {␊ - document$2.exports = document;␊ + document$1.exports = document;␊ } else {␊ - document$2.exports = { fake: true };␊ + document$1.exports = { fake: true };␊ }␊ ␊ - var document$1 = document$2.exports;␊ - ␊ - t.deepEqual(document$1, { real: true });␊ + t.deepEqual(document$1.exports, { real: true });␊ `, } @@ -158,6 +154,27 @@ Generated by [AVA](https://avajs.dev). `, } +## cjs-extension + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var _export = {␊ + test: 42␊ + };␊ + ␊ + const { test } = _export;␊ + ␊ + t.is(test, 42);␊ + ␊ + module.exports = main;␊ + `, + } + ## custom-options > Snapshot 1 @@ -165,7 +182,7 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - console.log('main');␊ + t.is('main', 'main');␊ `, } @@ -273,16 +290,14 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var x$2 = {exports: {}};␊ + var x$1 = {exports: {}};␊ ␊ const x = {};␊ ␊ - x$2.exports = x;␊ - x$2.exports.default = x;␊ - ␊ - var x$1 = x$2.exports;␊ + x$1.exports = x;␊ + x$1.exports.default = x;␊ ␊ - t.is(x$1.default, x$1);␊ + t.is(x$1.exports.default, x$1.exports);␊ `, } @@ -293,16 +308,14 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var x$2 = {exports: {}};␊ + var x$1 = {exports: {}};␊ ␊ const x = {};␊ ␊ - x$2.exports = x;␊ - x$2.exports.default = 42;␊ + x$1.exports = x;␊ + x$1.exports.default = 42;␊ ␊ - var x$1 = x$2.exports;␊ - ␊ - t.deepEqual(x$1, { default: 42 });␊ + t.deepEqual(x$1.exports, { default: 42 });␊ `, } @@ -334,119 +347,60 @@ Generated by [AVA](https://avajs.dev). `, } -## dynamic-module-require +## dynamic-require > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var submodule;␊ + var hasRequiredSubmodule;␊ ␊ - function createModule(modulePath) {␊ - return {␊ - path: modulePath,␊ - exports: {},␊ - require: function (path, base) {␊ - return commonjsRequire(path, base == null ? modulePath : base);␊ - }␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = function () {␊ + return 'Hello there';␊ };␊ + return submodule;␊ }␊ ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ - ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + var dynamicModules;␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require/submodule.js": requireSubmodule␊ + });␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ + 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.');␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ - }␊ + commonjsRequire.resolve = commonjsResolve;␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -460,15 +414,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -480,73 +428,62 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main$1 = createModule("/$$rollup_base$$/fixtures/function/dynamic-module-require");␊ - ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-module-require/submodule.js", function (module, exports) {␊ - module.exports = function () {␊ - return 'Hello there';␊ - };␊ + function join () {␊ + if (arguments.length === 0) return '.';␊ + var joined;␊ + for (var i = 0; i < arguments.length; ++i) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ + if (joined === undefined)␊ + joined = arg;␊ + else␊ + joined += '/' + arg;␊ + }␊ + }␊ + if (joined === undefined) return '.';␊ + return joined;␊ + }␊ ␊ - });␊ + var main = {};␊ ␊ - (function (module) {␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ let message;␊ ␊ function takeModule(withName) {␊ - return module.require(`./${withName}`);␊ + return commonjsRequire(`./${withName}`, "/$$rollup_base$$/fixtures/function/dynamic-require");␊ }␊ ␊ try {␊ @@ -557,117 +494,85 @@ Generated by [AVA](https://avajs.dev). }␊ ␊ t.is(message, 'Hello there');␊ - }(main$1));␊ - ␊ - var main = main$1.exports;␊ ␊ module.exports = main;␊ `, } -## dynamic-require +## dynamic-require-absolute-import > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var direct;␊ + var hasRequiredDirect;␊ ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function requireDirect () {␊ + if (hasRequiredDirect) return direct;␊ + hasRequiredDirect = 1;␊ + direct = 'direct';␊ + return direct;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + var nested;␊ + var hasRequiredNested;␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + function requireNested () {␊ + if (hasRequiredNested) return nested;␊ + hasRequiredNested = 1;␊ + nested = 'nested';␊ + return nested;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ + var parent;␊ + var hasRequiredParent;␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function requireParent () {␊ + if (hasRequiredParent) return parent;␊ + hasRequiredParent = 1;␊ + parent = 'parent';␊ + return parent;␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + var dynamicModules;␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/sub/node_modules/module/direct.js": requireDirect,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/sub/node_modules/module/nested/nested.js": requireNested,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/node_modules/parent-module/parent.js": requireParent␊ + });␊ + }␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + 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.');␊ + }␊ ␊ - return '.';␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + commonjsRequire.resolve = commonjsResolve;␊ + ␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -681,15 +586,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -701,108 +600,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main = {};␊ - ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require/submodule.js", function (module, exports) {␊ - module.exports = function () {␊ - return 'Hello there';␊ - };␊ - ␊ - });␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - let message;␊ - ␊ - function takeModule(withName) {␊ - return commonjsRequire(`./${withName}`,"/$$rollup_base$$/fixtures/function/dynamic-require");␊ - }␊ - ␊ - try {␊ - const submodule = takeModule('submodule');␊ - message = submodule();␊ - } catch (err) {␊ - ({ message } = err);␊ - }␊ - ␊ - t.is(message, 'Hello there');␊ - ␊ - module.exports = main;␊ - `, - } - -## dynamic-require-absolute-import - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$3 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -820,180 +627,35 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ + if (arguments.length === 0) return '.';␊ var joined;␊ for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ if (joined === undefined)␊ - joined = arg;␊ + joined = arg;␊ else␊ - joined += '/' + arg;␊ - }␊ + joined += '/' + arg;␊ + }␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ + if (joined === undefined) return '.';␊ return joined;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ - ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ - }␊ - ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ - var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ - path = normalize(path);␊ - var relPath;␊ - if (path[0] === '/') {␊ - originalModuleDir = '/';␊ - }␊ - while (true) {␊ - if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ - } else {␊ - relPath = normalize(join('node_modules', path));␊ - }␊ - ␊ - if (relPath.endsWith('/..')) {␊ - break; // Travelled too far up, avoid infinite loop␊ - }␊ - ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - }␊ - if (!shouldTryNodeModules) break;␊ - var nextDir = normalize(originalModuleDir + '/..');␊ - if (nextDir === originalModuleDir) break;␊ - originalModuleDir = nextDir;␊ - }␊ - return null;␊ - }␊ - ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ var main = {};␊ ␊ - const commonjsRegister$2 = commonjsRegister$3;␊ - commonjsRegister$2("/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/sub/node_modules/module/direct.js", function (module, exports) {␊ - module.exports = 'direct';␊ - ␊ - });␊ - ␊ - const commonjsRegister$1 = commonjsRegister$3;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/sub/node_modules/module/nested/nested.js", function (module, exports) {␊ - module.exports = 'nested';␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$3;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/node_modules/parent-module/parent.js", function (module, exports) {␊ - module.exports = 'parent';␊ - ␊ - });␊ - ␊ var submodule = {};␊ ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule(name) {␊ - return commonjsRequire(name,"/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/sub");␊ + return commonjsRequire(name, "/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/sub");␊ }␊ ␊ submodule.moduleDirect = takeModule('module/direct');␊ @@ -1012,118 +674,69 @@ Generated by [AVA](https://avajs.dev). `, } -## dynamic-require-cache-reference +## dynamic-require-code-splitting > Snapshot 1 { - 'main.js': `'use strict';␊ + 'generated-lib2.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var target1;␊ + var hasRequiredTarget1;␊ ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function requireTarget1 () {␊ + if (hasRequiredTarget1) return target1;␊ + hasRequiredTarget1 = 1;␊ + target1 = '1';␊ + return target1;␊ }␊ ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ + var target2;␊ + var hasRequiredTarget2;␊ + ␊ + function requireTarget2 () {␊ + if (hasRequiredTarget2) return target2;␊ + hasRequiredTarget2 = 1;␊ + target2 = '2';␊ + return target2;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + var dynamicModules;␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting/target1.js": requireTarget1,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting/target2.js": requireTarget2␊ + });␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ + 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.');␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ - }␊ + commonjsRequire.resolve = commonjsResolve;␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -1137,15 +750,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -1157,139 +764,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main = {};␊ - ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module/index.js", function (module, exports) {␊ - module.exports = {␊ - foo: 'bar',␊ - };␊ - ␊ - });␊ - ␊ - function mv(from, to) {␊ - for (let [key, value] of Object.entries(from)) {␊ - to[key] = value;␊ - }␊ - }␊ - ␊ - function clear(obj) {␊ - for (let key of Array.from(Object.keys(obj))) {␊ - delete obj[key];␊ - }␊ - }␊ - ␊ - var stealthy = function stealth(cacheObject, cb) {␊ - let orig = Object.create(null);␊ - ␊ - mv(cacheObject, orig);␊ - clear(cacheObject);␊ - ␊ - let res = cb();␊ - ␊ - clear(cacheObject);␊ - mv(orig, cacheObject);␊ - ␊ - return res;␊ - };␊ - ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module2/index.js", function (module, exports) {␊ - const stealthRequire = stealthy;␊ - ␊ - module.exports = stealthRequire(commonjsRequire.cache, () => {␊ - let m = commonjsRequire("custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module2");␊ - m.foo = 'baz';␊ - return m;␊ - });␊ - ␊ - });␊ - ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module/index.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module2", "/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module2/index.js");␊ - ␊ - const a = commonjsRequire("custom-module2", "/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference");␊ - const b = commonjsRequire("custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference");␊ - ␊ - t.is(a.foo, 'baz');␊ - t.is(b.foo, 'bar');␊ - ␊ - module.exports = main;␊ - `, - } - -## dynamic-require-code-splitting - -> Snapshot 1 - - { - 'generated-lib2.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -1307,1179 +791,145 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ + if (arguments.length === 0) return '.';␊ var joined;␊ for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ if (joined === undefined)␊ - joined = arg;␊ + joined = arg;␊ else␊ - joined += '/' + arg;␊ - }␊ + joined += '/' + arg;␊ + }␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ + if (joined === undefined) return '.';␊ return joined;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + let message;␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ + for (const index of [1, 2]) {␊ + try {␊ + message = commonjsRequire(`./target${index}.js`, "/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting");␊ + } catch (err) {␊ + ({ message } = err);␊ }␊ + t.is(message, index.toString());␊ + }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + exports.commonjsRequire = commonjsRequire;␊ + `, + 'main.js': `'use strict';␊ ␊ - return '.';␊ - }␊ + var lib2 = require('./generated-lib2.js');␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ - var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ - path = normalize(path);␊ - var relPath;␊ - if (path[0] === '/') {␊ - originalModuleDir = '/';␊ - }␊ - while (true) {␊ - if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ - } else {␊ - relPath = normalize(join('node_modules', path));␊ - }␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - if (relPath.endsWith('/..')) {␊ - break; // Travelled too far up, avoid infinite loop␊ - }␊ + let message;␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - }␊ - if (!shouldTryNodeModules) break;␊ - var nextDir = normalize(originalModuleDir + '/..');␊ - if (nextDir === originalModuleDir) break;␊ - originalModuleDir = nextDir;␊ - }␊ - return null;␊ + for (const index of [1, 2]) {␊ + try {␊ + message = lib2.commonjsRequire(`./target${index}.js`, "/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting");␊ + } catch (err) {␊ + ({ message } = err);␊ + }␊ + t.is(message, index.toString());␊ }␊ - ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting/target1.js", function (module, exports) {␊ - module.exports = '1';␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting/target2.js", function (module, exports) {␊ - module.exports = '2';␊ - ␊ - });␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - let message;␊ - ␊ - for (const index of [1, 2]) {␊ - try {␊ - message = commonjsRequire(`./target${index}.js`,"/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting");␊ - } catch (err) {␊ - ({ message } = err);␊ - }␊ - t.is(message, index.toString());␊ - }␊ - ␊ - exports.commonjsRequire = commonjsRequire;␊ - `, - 'main.js': `'use strict';␊ - ␊ - var lib2 = require('./generated-lib2.js');␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - let message;␊ - ␊ - for (const index of [1, 2]) {␊ - try {␊ - message = lib2.commonjsRequire(`./target${index}.js`,"/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting");␊ - } catch (err) {␊ - ({ message } = err);␊ - }␊ - t.is(message, index.toString());␊ - }␊ - `, - 'main2.js': `'use strict';␊ + `, + 'main2.js': `'use strict';␊ ␊ require('./generated-lib2.js');␊ ␊ `, } - -## dynamic-require-es-entry - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ - ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ - }␊ - ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ - ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ - ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ - }␊ - ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ - var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ - path = normalize(path);␊ - var relPath;␊ - if (path[0] === '/') {␊ - originalModuleDir = '/';␊ - }␊ - while (true) {␊ - if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ - } else {␊ - relPath = normalize(join('node_modules', path));␊ - }␊ - ␊ - if (relPath.endsWith('/..')) {␊ - break; // Travelled too far up, avoid infinite loop␊ - }␊ - ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - }␊ - if (!shouldTryNodeModules) break;␊ - var nextDir = normalize(originalModuleDir + '/..');␊ - if (nextDir === originalModuleDir) break;␊ - originalModuleDir = nextDir;␊ - }␊ - return null;␊ - }␊ - ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-es-entry/submodule.js", function (module, exports) {␊ - module.exports = 'submodule';␊ - ␊ - });␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - function takeModule(withName) {␊ - return commonjsRequire(`./${withName}`,"/$$rollup_base$$/fixtures/function/dynamic-require-es-entry");␊ - }␊ - ␊ - var importer = takeModule('submodule.js');␊ - ␊ - t.is(importer, 'submodule');␊ - `, - } - -## dynamic-require-extensions - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ - ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ - }␊ - ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ - ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ - ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ - }␊ - ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ - var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ - path = normalize(path);␊ - var relPath;␊ - if (path[0] === '/') {␊ - originalModuleDir = '/';␊ - }␊ - while (true) {␊ - if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ - } else {␊ - relPath = normalize(join('node_modules', path));␊ - }␊ - ␊ - if (relPath.endsWith('/..')) {␊ - break; // Travelled too far up, avoid infinite loop␊ - }␊ - ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - }␊ - if (!shouldTryNodeModules) break;␊ - var nextDir = normalize(originalModuleDir + '/..');␊ - if (nextDir === originalModuleDir) break;␊ - originalModuleDir = nextDir;␊ - }␊ - return null;␊ - }␊ - ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main = {};␊ - ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-extensions/submodule.js", function (module, exports) {␊ - module.exports = { name: 'submodule', value: null };␊ - ␊ - });␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - function takeModule(withName) {␊ - return commonjsRequire(`./${withName}`,"/$$rollup_base$$/fixtures/function/dynamic-require-extensions");␊ - }␊ - ␊ - const withExtension = takeModule('submodule.js');␊ - const withoutExtension = takeModule('submodule');␊ - ␊ - t.is(withExtension.name, 'submodule');␊ - t.is(withoutExtension.name, 'submodule');␊ - ␊ - withExtension.value = 'mutated';␊ - ␊ - t.is(withoutExtension.value, 'mutated');␊ - ␊ - module.exports = main;␊ - `, - } - -## dynamic-require-fallback - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var main = {};␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - function takeModule(withName) {␊ - return require(withName);␊ - }␊ - ␊ - // The bundled code will run from test/helpers/util.js␊ - t.is(takeModule('../fixtures/function/dynamic-require-fallback/dep.js'), 'dep');␊ - ␊ - module.exports = main;␊ - `, - } - -## dynamic-require-from-es-import - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ - ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ - }␊ - ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ - ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ - ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ - }␊ - ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ - var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ - path = normalize(path);␊ - var relPath;␊ - if (path[0] === '/') {␊ - originalModuleDir = '/';␊ - }␊ - while (true) {␊ - if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ - } else {␊ - relPath = normalize(join('node_modules', path));␊ - }␊ - ␊ - if (relPath.endsWith('/..')) {␊ - break; // Travelled too far up, avoid infinite loop␊ - }␊ - ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - }␊ - if (!shouldTryNodeModules) break;␊ - var nextDir = normalize(originalModuleDir + '/..');␊ - if (nextDir === originalModuleDir) break;␊ - originalModuleDir = nextDir;␊ - }␊ - return null;␊ - }␊ - ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-from-es-import/submodule.js", function (module, exports) {␊ - module.exports = 'submodule';␊ - ␊ - });␊ - ␊ - var submodule = commonjsRequire("/$$rollup_base$$/fixtures/function/dynamic-require-from-es-import/submodule.js", "/$$rollup_base$$/fixtures/function/dynamic-require-from-es-import");␊ - ␊ - t.is(submodule, 'submodule');␊ - `, - } - -## dynamic-require-globs - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$3 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ - ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ - }␊ - ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ - ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ - ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ - }␊ - ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ - var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ - path = normalize(path);␊ - var relPath;␊ - if (path[0] === '/') {␊ - originalModuleDir = '/';␊ - }␊ - while (true) {␊ - if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ - } else {␊ - relPath = normalize(join('node_modules', path));␊ - }␊ - ␊ - if (relPath.endsWith('/..')) {␊ - break; // Travelled too far up, avoid infinite loop␊ - }␊ - ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - }␊ - if (!shouldTryNodeModules) break;␊ - var nextDir = normalize(originalModuleDir + '/..');␊ - if (nextDir === originalModuleDir) break;␊ - originalModuleDir = nextDir;␊ - }␊ - return null;␊ - }␊ - ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main = {};␊ - ␊ - const commonjsRegister$2 = commonjsRegister$3;␊ - commonjsRegister$2("/$$rollup_base$$/fixtures/function/dynamic-require-globs/submodule1.js", function (module, exports) {␊ - module.exports = 'submodule1';␊ - ␊ - });␊ - ␊ - const commonjsRegister$1 = commonjsRegister$3;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-globs/submodule2.js", function (module, exports) {␊ - module.exports = 'submodule2';␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$3;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-globs/extramodule1.js", function (module, exports) {␊ - module.exports = 'extramodule1';␊ - ␊ - });␊ + +## dynamic-require-different-loader + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ + var submodule2;␊ + var hasRequiredSubmodule2;␊ ␊ - function takeModule(withName) {␊ - return commonjsRequire(`./${withName}`,"/$$rollup_base$$/fixtures/function/dynamic-require-globs");␊ + function requireSubmodule2 () {␊ + if (hasRequiredSubmodule2) return submodule2;␊ + hasRequiredSubmodule2 = 1;␊ + submodule2 = function () {␊ + return 'Hello there';␊ + };␊ + return submodule2;␊ }␊ ␊ - t.is(takeModule('submodule1.js'), 'submodule1');␊ - t.is(takeModule('submodule2.js'), 'submodule2');␊ - t.is(takeModule('extramodule1.js'), 'extramodule1');␊ - t.throws(() => takeModule('extramodule2.js'), {␊ - message:␊ - 'Could not dynamically require "./extramodule2.js". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'␊ - });␊ + const fn = requireSubmodule2();␊ + ␊ + var main = fn();␊ ␊ module.exports = main;␊ `, } -## dynamic-require-instances +## dynamic-require-es-entry > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ + var submodule;␊ + var hasRequiredSubmodule;␊ ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = 'submodule';␊ + return submodule;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + var dynamicModules;␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-es-entry/submodule.js": requireSubmodule␊ + });␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ + 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.');␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ - }␊ + commonjsRequire.resolve = commonjsResolve;␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -2493,15 +943,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -2513,113 +957,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main = {};␊ - ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-instances/direct/index.js", function (module, exports) {␊ - module.exports = { name: 'direct', value: null };␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-instances/package/main.js", function (module, exports) {␊ - module.exports = { name: 'package', value: null };␊ - ␊ - });␊ - ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-instances/direct", "/$$rollup_base$$/fixtures/function/dynamic-require-instances/direct/index.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-instances/package", "/$$rollup_base$$/fixtures/function/dynamic-require-instances/package/main.js");␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - function takeModule(withName) {␊ - return commonjsRequire(withName,"/$$rollup_base$$/fixtures/function/dynamic-require-instances");␊ - }␊ - ␊ - takeModule('./direct').value = 'direct-instance';␊ - t.is(takeModule('./direct/index.js').value, 'direct-instance');␊ - t.is(commonjsRequire("./direct/index.js", "/$$rollup_base$$/fixtures/function/dynamic-require-instances").value, 'direct-instance');␊ - ␊ - takeModule('./package').value = 'package-instance';␊ - t.is(takeModule('./package/main.js').value, 'package-instance');␊ - t.is(commonjsRequire("./package/main.js", "/$$rollup_base$$/fixtures/function/dynamic-require-instances").value, 'package-instance');␊ - ␊ - module.exports = main;␊ - `, - } - -## dynamic-require-json - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -2637,71 +984,125 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ + if (arguments.length === 0) return '.';␊ var joined;␊ for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ if (joined === undefined)␊ - joined = arg;␊ + joined = arg;␊ else␊ - joined += '/' + arg;␊ - }␊ + joined += '/' + arg;␊ + }␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ + if (joined === undefined) return '.';␊ return joined;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + function takeModule(withName) {␊ + return commonjsRequire(`./${withName}`, "/$$rollup_base$$/fixtures/function/dynamic-require-es-entry");␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + var importer = takeModule('submodule.js');␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + t.is(importer, 'submodule');␊ + `, + } + +## dynamic-require-es-mixed-helpers + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var submodule;␊ + var hasRequiredSubmodule;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + commonjsGlobal.hasSubmoduleRun = true;␊ + submodule = 'submodule';␊ + return submodule;␊ + }␊ + ␊ + t.is(global.hasSubmoduleRun, undefined, 'before require');␊ + ␊ + // eslint-disable-next-line global-require␊ + var result = requireSubmodule();␊ + ␊ + t.is(global.hasSubmoduleRun, true, 'after require');␊ + delete global.hasSubmoduleRun;␊ + ␊ + t.is(result, 'submodule');␊ + `, + } + +## dynamic-require-extensions + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var submodule;␊ + var hasRequiredSubmodule;␊ + ␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = { name: 'submodule', value: null };␊ + return submodule;␊ + }␊ + ␊ + var dynamicModules;␊ + ␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-extensions/submodule.js": requireSubmodule␊ + });␊ + }␊ + ␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + 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.');␊ + }␊ ␊ - return '.';␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + commonjsRequire.resolve = commonjsResolve;␊ + ␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -2715,15 +1116,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -2735,221 +1130,195 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function join () {␊ + if (arguments.length === 0) return '.';␊ + var joined;␊ + for (var i = 0; i < arguments.length; ++i) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ + if (joined === undefined)␊ + joined = arg;␊ + else␊ + joined += '/' + arg;␊ + }␊ + }␊ + if (joined === undefined) return '.';␊ + return joined;␊ + }␊ ␊ var main = {};␊ ␊ - var value = "present";␊ - var require$$1 = {␊ - value: value␊ - };␊ - ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-json/dynamic.json", function (module, exports) {␊ - module.exports = require$$1;␊ - });␊ - ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule(withName) {␊ - return commonjsRequire(`./${withName}`,"/$$rollup_base$$/fixtures/function/dynamic-require-json");␊ + return commonjsRequire(`./${withName}`, "/$$rollup_base$$/fixtures/function/dynamic-require-extensions");␊ }␊ ␊ - t.deepEqual(takeModule('dynamic.json'), { value: 'present' });␊ - t.deepEqual(takeModule('dynamic'), { value: 'present' });␊ + const withExtension = takeModule('submodule.js');␊ + const withoutExtension = takeModule('submodule');␊ + ␊ + t.is(withExtension.name, 'submodule');␊ + t.is(withoutExtension.name, 'submodule');␊ + ␊ + withExtension.value = 'mutated';␊ + ␊ + t.is(withoutExtension.value, 'mutated');␊ ␊ module.exports = main;␊ `, } -## dynamic-require-no-fallback +## dynamic-require-fallback > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - function commonjsRequire (path) {␊ - 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.');␊ - }␊ - ␊ var main = {};␊ ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule(withName) {␊ - return commonjsRequire(withName);␊ + return require(withName);␊ }␊ ␊ - t.throws(() => takeModule('./dep.js'), {␊ - message:␊ - 'Could not dynamically require "./dep.js". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'␊ - });␊ + // The bundled code will run from test/helpers/util.js␊ + t.is(takeModule('../fixtures/function/dynamic-require-fallback/dep.js'), 'dep');␊ ␊ module.exports = main;␊ `, } -## dynamic-require-package +## dynamic-require-from-es-import > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var submodule;␊ + var hasRequiredSubmodule;␊ ␊ - function commonjsRegister$3 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = 'submodule';␊ + return submodule;␊ }␊ ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ - }␊ + var submoduleExports = requireSubmodule();␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + t.is(submoduleExports, 'submodule');␊ + `, + } + +## dynamic-require-globs + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + var submodule1;␊ + var hasRequiredSubmodule1;␊ + ␊ + function requireSubmodule1 () {␊ + if (hasRequiredSubmodule1) return submodule1;␊ + hasRequiredSubmodule1 = 1;␊ + submodule1 = 'submodule1';␊ + return submodule1;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var submodule2;␊ + var hasRequiredSubmodule2;␊ ␊ - return joined;␊ + function requireSubmodule2 () {␊ + if (hasRequiredSubmodule2) return submodule2;␊ + hasRequiredSubmodule2 = 1;␊ + submodule2 = 'submodule2';␊ + return submodule2;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ + var extramodule1;␊ + var hasRequiredExtramodule1;␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + function requireExtramodule1 () {␊ + if (hasRequiredExtramodule1) return extramodule1;␊ + hasRequiredExtramodule1 = 1;␊ + extramodule1 = 'extramodule1';␊ + return extramodule1;␊ + }␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + var dynamicModules;␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-globs/submodule1.js": requireSubmodule1,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-globs/submodule2.js": requireSubmodule2,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-globs/extramodule1.js": requireExtramodule1␊ + });␊ + }␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + 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.');␊ + }␊ ␊ - return '.';␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + commonjsRequire.resolve = commonjsResolve;␊ + ␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -2963,15 +1332,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -2983,141 +1346,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main = {};␊ - ␊ - const commonjsRegister$2 = commonjsRegister$3;␊ - commonjsRegister$2("/$$rollup_base$$/fixtures/function/dynamic-require-package/entry.js", function (module, exports) {␊ - module.exports = 'same-directory';␊ - ␊ - });␊ - ␊ - const commonjsRegister$1 = commonjsRegister$3;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-package/sub/entry.js", function (module, exports) {␊ - module.exports = 'sub';␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$3;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-package/node_modules/custom-module/entry.js", function (module, exports) {␊ - module.exports = 'custom-module';␊ - ␊ - });␊ - ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-package", "/$$rollup_base$$/fixtures/function/dynamic-require-package/entry.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-package/sub", "/$$rollup_base$$/fixtures/function/dynamic-require-package/sub/entry.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-package/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-package/node_modules/custom-module/entry.js");␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - function takeModule$1(name) {␊ - return commonjsRequire(name,"/$$rollup_base$$/fixtures/function/dynamic-require-package/sub");␊ - }␊ - ␊ - var sub = {␊ - parent: takeModule$1('..'),␊ - customModule: takeModule$1('custom-module')␊ - };␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - function takeModule(name) {␊ - return commonjsRequire(name,"/$$rollup_base$$/fixtures/function/dynamic-require-package");␊ - }␊ - ␊ - t.is(takeModule('.'), 'same-directory');␊ - t.is(takeModule('./'), 'same-directory');␊ - t.is(takeModule('.//'), 'same-directory');␊ - ␊ - t.is(takeModule('./sub'), 'sub');␊ - ␊ - t.is(takeModule('custom-module'), 'custom-module');␊ - t.deepEqual(sub, { parent: 'same-directory', customModule: 'custom-module' });␊ - ␊ - module.exports = main;␊ - `, - } - -## dynamic-require-package-sub - -> Snapshot 1 - - { - 'entry.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ - ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -3135,201 +1373,148 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ + if (arguments.length === 0) return '.';␊ var joined;␊ for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ if (joined === undefined)␊ - joined = arg;␊ + joined = arg;␊ else␊ - joined += '/' + arg;␊ - }␊ + joined += '/' + arg;␊ + }␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ + if (joined === undefined) return '.';␊ return joined;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + var main = {};␊ + ␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + function takeModule(withName) {␊ + return commonjsRequire(`./${withName}`, "/$$rollup_base$$/fixtures/function/dynamic-require-globs");␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + t.is(takeModule('submodule1.js'), 'submodule1');␊ + t.is(takeModule('submodule2.js'), 'submodule2');␊ + t.is(takeModule('extramodule1.js'), 'extramodule1');␊ + t.throws(() => takeModule('extramodule2.js'), {␊ + message:␊ + 'Could not dynamically require "./extramodule2.js". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'␊ + });␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + module.exports = main;␊ + `, + } + +## dynamic-require-instances + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var direct;␊ + var hasRequiredDirect;␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + function requireDirect () {␊ + if (hasRequiredDirect) return direct;␊ + hasRequiredDirect = 1;␊ + direct = { name: 'direct', value: null };␊ + return direct;␊ + }␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + var main$1;␊ + var hasRequiredMain;␊ ␊ - return '.';␊ + function requireMain () {␊ + if (hasRequiredMain) return main$1;␊ + hasRequiredMain = 1;␊ + main$1 = { name: 'package', value: null };␊ + return main$1;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ - var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ - path = normalize(path);␊ - var relPath;␊ - if (path[0] === '/') {␊ - originalModuleDir = '/';␊ - }␊ - while (true) {␊ - if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ - } else {␊ - relPath = normalize(join('node_modules', path));␊ - }␊ + var dynamicModules;␊ ␊ - if (relPath.endsWith('/..')) {␊ - break; // Travelled too far up, avoid infinite loop␊ - }␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-instances/direct": requireDirect,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-instances/direct/index.js": requireDirect,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-instances/package": requireMain,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-instances/package/main.js": requireMain␊ + });␊ + }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - }␊ - if (!shouldTryNodeModules) break;␊ - var nextDir = normalize(originalModuleDir + '/..');␊ - if (nextDir === originalModuleDir) break;␊ - originalModuleDir = nextDir;␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ }␊ - return null;␊ + 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.');␊ }␊ ␊ function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ if (resolvedPath !== null) {␊ return resolvedPath;␊ }␊ return require.resolve(path);␊ }␊ ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ commonjsRequire.resolve = commonjsResolve;␊ ␊ - var entry = {};␊ - ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-package-sub/node_modules/custom-module/entry.js", function (module, exports) {␊ - module.exports = 'custom-module';␊ - ␊ - });␊ - ␊ - var main = "./entry.js";␊ - var require$$1 = {␊ - main: main␊ - };␊ - ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-package-sub/node_modules/custom-module/package.json", function (module, exports) {␊ - module.exports = require$$1;␊ - });␊ - ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-package-sub/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-package-sub/node_modules/custom-module/entry.js");␊ - ␊ - t.is(commonjsRequire("custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-package-sub/sub"), 'custom-module');␊ - ␊ - module.exports = entry;␊ - `, - } - -## dynamic-require-relative-paths - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ + var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ + path = normalize(path);␊ + var relPath;␊ + if (path[0] === '/') {␊ + originalModuleDir = '/';␊ + }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ + while (true) {␊ + if (!shouldTryNodeModules) {␊ + relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ + } else if (originalModuleDir) {␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + } else {␊ + relPath = normalize(join('node_modules', path));␊ + }␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + if (relPath.endsWith('/..')) {␊ + break; // Travelled too far up, avoid infinite loop␊ + }␊ ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ + return resolvedPath;␊ + }␊ + }␊ + if (!shouldTryNodeModules) break;␊ + var nextDir = normalize(originalModuleDir + '/..');␊ + if (nextDir === originalModuleDir) break;␊ + originalModuleDir = nextDir;␊ + }␊ + return null;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ + }␊ ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ @@ -3348,71 +1533,94 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ + if (arguments.length === 0) return '.';␊ var joined;␊ for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ if (joined === undefined)␊ - joined = arg;␊ + joined = arg;␊ else␊ - joined += '/' + arg;␊ - }␊ + joined += '/' + arg;␊ + }␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ + if (joined === undefined) return '.';␊ return joined;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + var main = {};␊ + ␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + function takeModule(withName) {␊ + return commonjsRequire(withName, "/$$rollup_base$$/fixtures/function/dynamic-require-instances");␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + takeModule('./direct').value = 'direct-instance';␊ + t.is(takeModule('./direct/index.js').value, 'direct-instance');␊ + t.is(requireDirect().value, 'direct-instance');␊ + ␊ + takeModule('./package').value = 'package-instance';␊ + t.is(takeModule('./package/main.js').value, 'package-instance');␊ + t.is(requireMain().value, 'package-instance');␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + module.exports = main;␊ + `, + } + +## dynamic-require-json + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var value = "present";␊ + var json0 = {␊ + value: value␊ + };␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var dynamicModules;␊ + ␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-json/dynamic.json": function () { return json0; }␊ + });␊ + }␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + 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.');␊ + }␊ ␊ - return '.';␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + commonjsRequire.resolve = commonjsResolve;␊ + ␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -3426,15 +1634,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -3446,197 +1648,174 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function join () {␊ + if (arguments.length === 0) return '.';␊ + var joined;␊ + for (var i = 0; i < arguments.length; ++i) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ + if (joined === undefined)␊ + joined = arg;␊ + else␊ + joined += '/' + arg;␊ + }␊ + }␊ + if (joined === undefined) return '.';␊ + return joined;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-relative-paths/sub/submodule.js", function (module, exports) {␊ - module.exports = 'submodule';␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - });␊ + function takeModule(withName) {␊ + return commonjsRequire(`./${withName}`, "/$$rollup_base$$/fixtures/function/dynamic-require-json");␊ + }␊ ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-relative-paths/sub/subsub/subsubmodule.js", function (module, exports) {␊ - module.exports = 'subsubmodule';␊ + t.deepEqual(takeModule('dynamic.json'), { value: 'present' });␊ + t.deepEqual(takeModule('dynamic'), { value: 'present' });␊ ␊ - });␊ + module.exports = main;␊ + `, + } + +## dynamic-require-no-fallback + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + function commonjsRequire(path) {␊ + 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.');␊ + }␊ + ␊ + var main = {};␊ ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - function takeModuleWithDelimiter(name, delimiter) {␊ - return commonjsRequire(`.${delimiter}${name.replace(/=/g, delimiter)}`,"/$$rollup_base$$/fixtures/function/dynamic-require-relative-paths");␊ + function takeModule(withName) {␊ + return commonjsRequire(withName);␊ }␊ ␊ - t.is(takeModuleWithDelimiter('sub=submodule.js', '/'), 'submodule');␊ - t.is(takeModuleWithDelimiter('sub=subsub=subsubmodule.js', '/'), 'subsubmodule');␊ - t.is(takeModuleWithDelimiter('sub=submodule.js', '\\\\'), 'submodule');␊ - t.is(takeModuleWithDelimiter('sub=subsub=subsubmodule.js', '\\\\'), 'subsubmodule');␊ + t.throws(() => takeModule('./dep.js'), {␊ + message:␊ + 'Could not dynamically require "./dep.js". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'␊ + });␊ ␊ module.exports = main;␊ `, } -## dynamic-require-resolve-index +## dynamic-require-package > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var entry$2;␊ + var hasRequiredEntry$2;␊ ␊ - function commonjsRegister$3 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function requireEntry$2 () {␊ + if (hasRequiredEntry$2) return entry$2;␊ + hasRequiredEntry$2 = 1;␊ + entry$2 = 'same-directory';␊ + return entry$2;␊ }␊ ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ + var entry$1;␊ + var hasRequiredEntry$1;␊ + ␊ + function requireEntry$1 () {␊ + if (hasRequiredEntry$1) return entry$1;␊ + hasRequiredEntry$1 = 1;␊ + entry$1 = 'sub';␊ + return entry$1;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + var entry;␊ + var hasRequiredEntry;␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + function requireEntry () {␊ + if (hasRequiredEntry) return entry;␊ + hasRequiredEntry = 1;␊ + entry = 'custom-module';␊ + return entry;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var dynamicModules;␊ ␊ - return joined;␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-package": requireEntry$2,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-package/entry.js": requireEntry$2,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-package/sub": requireEntry$1,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-package/sub/entry.js": requireEntry$1,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-package/node_modules/custom-module": requireEntry,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-package/node_modules/custom-module/entry.js": requireEntry␊ + });␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + 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.');␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + commonjsRequire.resolve = commonjsResolve;␊ + ␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -3650,15 +1829,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -3670,85 +1843,60 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function join () {␊ + if (arguments.length === 0) return '.';␊ + var joined;␊ + for (var i = 0; i < arguments.length; ++i) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ + if (joined === undefined)␊ + joined = arg;␊ + else␊ + joined += '/' + arg;␊ + }␊ + }␊ + if (joined === undefined) return '.';␊ + return joined;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister$2 = commonjsRegister$3;␊ - commonjsRegister$2("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/index.js", function (module, exports) {␊ - module.exports = 'same-directory';␊ - ␊ - });␊ - ␊ - const commonjsRegister$1 = commonjsRegister$3;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/sub/index.js", function (module, exports) {␊ - module.exports = 'sub';␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$3;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/node_modules/custom-module/index.js", function (module, exports) {␊ - module.exports = 'custom-module';␊ - ␊ - });␊ - ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/index.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/sub", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/sub/index.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/node_modules/custom-module/index.js");␊ - ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule$1(name) {␊ - return commonjsRequire(name,"/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/sub");␊ + return commonjsRequire(name, "/$$rollup_base$$/fixtures/function/dynamic-require-package/sub");␊ }␊ ␊ var sub = {␊ @@ -3759,7 +1907,7 @@ Generated by [AVA](https://avajs.dev). /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule(name) {␊ - return commonjsRequire(name,"/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index");␊ + return commonjsRequire(name, "/$$rollup_base$$/fixtures/function/dynamic-require-package");␊ }␊ ␊ t.is(takeModule('.'), 'same-directory');␊ @@ -3775,35 +1923,130 @@ Generated by [AVA](https://avajs.dev). `, } -## dynamic-require-resolve-reference +## dynamic-require-package-sub + +> Snapshot 1 + + { + 'entry.js': `'use strict';␊ + ␊ + var entry$1;␊ + var hasRequiredEntry;␊ + ␊ + function requireEntry () {␊ + if (hasRequiredEntry) return entry$1;␊ + hasRequiredEntry = 1;␊ + entry$1 = 'custom-module';␊ + return entry$1;␊ + }␊ + ␊ + var entry = {};␊ + ␊ + t.is(requireEntry(), 'custom-module');␊ + ␊ + module.exports = entry;␊ + `, + } + +## dynamic-require-relative-paths > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var submodule;␊ + var hasRequiredSubmodule;␊ + ␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = 'submodule';␊ + return submodule;␊ + }␊ + ␊ + var subsubmodule;␊ + var hasRequiredSubsubmodule;␊ + ␊ + function requireSubsubmodule () {␊ + if (hasRequiredSubsubmodule) return subsubmodule;␊ + hasRequiredSubsubmodule = 1;␊ + subsubmodule = 'subsubmodule';␊ + return subsubmodule;␊ + }␊ ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + var dynamicModules;␊ + ␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-relative-paths/sub/submodule.js": requireSubmodule,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-relative-paths/sub/subsub/subsubmodule.js": requireSubsubmodule␊ + });␊ }␊ ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ }␊ + 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.');␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + }␊ + ␊ + commonjsRequire.resolve = commonjsResolve;␊ + ␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ + var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ + path = normalize(path);␊ + var relPath;␊ + if (path[0] === '/') {␊ + originalModuleDir = '/';␊ + }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ + while (true) {␊ + if (!shouldTryNodeModules) {␊ + relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ + } else if (originalModuleDir) {␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + } else {␊ + relPath = normalize(join('node_modules', path));␊ + }␊ + ␊ + if (relPath.endsWith('/..')) {␊ + break; // Travelled too far up, avoid infinite loop␊ + }␊ + ␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ + return resolvedPath;␊ + }␊ + }␊ + if (!shouldTryNodeModules) break;␊ + var nextDir = normalize(originalModuleDir + '/..');␊ + if (nextDir === originalModuleDir) break;␊ + originalModuleDir = nextDir;␊ + }␊ + return null;␊ + }␊ + ␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ + }␊ ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ @@ -3822,71 +2065,121 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ + if (arguments.length === 0) return '.';␊ var joined;␊ for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ if (joined === undefined)␊ - joined = arg;␊ + joined = arg;␊ else␊ - joined += '/' + arg;␊ - }␊ + joined += '/' + arg;␊ + }␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ + if (joined === undefined) return '.';␊ return joined;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + var main = {};␊ + ␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + function takeModuleWithDelimiter(name, delimiter) {␊ + return commonjsRequire(`.${delimiter}${name.replace(/=/g, delimiter)}`, "/$$rollup_base$$/fixtures/function/dynamic-require-relative-paths");␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + t.is(takeModuleWithDelimiter('sub=submodule.js', '/'), 'submodule');␊ + t.is(takeModuleWithDelimiter('sub=subsub=subsubmodule.js', '/'), 'subsubmodule');␊ + t.is(takeModuleWithDelimiter('sub=submodule.js', '\\\\'), 'submodule');␊ + t.is(takeModuleWithDelimiter('sub=subsub=subsubmodule.js', '\\\\'), 'subsubmodule');␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + module.exports = main;␊ + `, + } + +## dynamic-require-resolve-index + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var dynamicRequireResolveIndex;␊ + var hasRequiredDynamicRequireResolveIndex;␊ + ␊ + function requireDynamicRequireResolveIndex () {␊ + if (hasRequiredDynamicRequireResolveIndex) return dynamicRequireResolveIndex;␊ + hasRequiredDynamicRequireResolveIndex = 1;␊ + dynamicRequireResolveIndex = 'same-directory';␊ + return dynamicRequireResolveIndex;␊ + }␊ + ␊ + var sub$1;␊ + var hasRequiredSub;␊ + ␊ + function requireSub () {␊ + if (hasRequiredSub) return sub$1;␊ + hasRequiredSub = 1;␊ + sub$1 = 'sub';␊ + return sub$1;␊ + }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var customModule;␊ + var hasRequiredCustomModule;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function requireCustomModule () {␊ + if (hasRequiredCustomModule) return customModule;␊ + hasRequiredCustomModule = 1;␊ + customModule = 'custom-module';␊ + return customModule;␊ + }␊ + ␊ + var dynamicModules;␊ + ␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index": requireDynamicRequireResolveIndex,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/index.js": requireDynamicRequireResolveIndex,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/sub": requireSub,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/sub/index.js": requireSub,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/node_modules/custom-module": requireCustomModule,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/node_modules/custom-module/index.js": requireCustomModule␊ + });␊ + }␊ + ␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + 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.');␊ + }␊ ␊ - return '.';␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + commonjsRequire.resolve = commonjsResolve;␊ + ␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -3900,15 +2193,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -3920,117 +2207,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main = {};␊ - ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module/index.js", function (module, exports) {␊ - module.exports = {␊ - foo: 'bar',␊ - };␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2/index.js", function (module, exports) {␊ - module.exports = () => {␊ - return commonjsRequire.resolve('custom-module',"/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2");␊ - };␊ - ␊ - });␊ - ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module/index.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2/index.js");␊ - ␊ - t.is(␊ - commonjsRequire("custom-module2", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference")(),␊ - '/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module'␊ - );␊ - ␊ - module.exports = main;␊ - `, - } - -## dynamic-require-root-circular - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ - ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -4048,71 +2234,128 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ + if (arguments.length === 0) return '.';␊ var joined;␊ for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ if (joined === undefined)␊ - joined = arg;␊ + joined = arg;␊ else␊ - joined += '/' + arg;␊ - }␊ + joined += '/' + arg;␊ + }␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ + if (joined === undefined) return '.';␊ return joined;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + var main = {};␊ + ␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + function takeModule$1(name) {␊ + return commonjsRequire(name, "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/sub");␊ + }␊ + ␊ + var sub = {␊ + parent: takeModule$1('..'),␊ + customModule: takeModule$1('custom-module')␊ + };␊ + ␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + function takeModule(name) {␊ + return commonjsRequire(name, "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index");␊ + }␊ + ␊ + t.is(takeModule('.'), 'same-directory');␊ + t.is(takeModule('./'), 'same-directory');␊ + t.is(takeModule('.//'), 'same-directory');␊ + ␊ + t.is(takeModule('./sub'), 'sub');␊ + ␊ + t.is(takeModule('custom-module'), 'custom-module');␊ + t.deepEqual(sub, { parent: 'same-directory', customModule: 'custom-module' });␊ + ␊ + module.exports = main;␊ + `, + } + +## dynamic-require-resolve-reference + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var customModule;␊ + var hasRequiredCustomModule;␊ + ␊ + function requireCustomModule () {␊ + if (hasRequiredCustomModule) return customModule;␊ + hasRequiredCustomModule = 1;␊ + customModule = {␊ + foo: 'bar',␊ + };␊ + return customModule;␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + var customModule2;␊ + var hasRequiredCustomModule2;␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + function requireCustomModule2 () {␊ + if (hasRequiredCustomModule2) return customModule2;␊ + hasRequiredCustomModule2 = 1;␊ + customModule2 = () => {␊ + return commonjsRequire.resolve('custom-module',"/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2");␊ + };␊ + return customModule2;␊ + }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var dynamicModules;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module": requireCustomModule,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module/index.js": requireCustomModule,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2": requireCustomModule2,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2/index.js": requireCustomModule2␊ + });␊ + }␊ + ␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + 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.');␊ + }␊ ␊ - return '.';␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + commonjsRequire.resolve = commonjsResolve;␊ + ␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -4126,15 +2369,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -4146,94 +2383,119 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function join () {␊ + if (arguments.length === 0) return '.';␊ + var joined;␊ + for (var i = 0; i < arguments.length; ++i) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ + if (joined === undefined)␊ + joined = arg;␊ + else␊ + joined += '/' + arg;␊ + }␊ + }␊ + if (joined === undefined) return '.';␊ + return joined;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module/index.js", function (module, exports) {␊ - const circular = commonjsRequire("./lib/circular", "/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module");␊ + t.is(␊ + requireCustomModule2()(),␊ + '/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module'␊ + );␊ + ␊ + module.exports = main;␊ + `, + } + +## dynamic-require-root-circular + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var customModule = {exports: {}};␊ ␊ - circular.extend1(module.exports);␊ + var circular = {};␊ ␊ - module.exports.get1 = function () {␊ - return 'all good';␊ - };␊ + var hasRequiredCircular;␊ ␊ - circular.extend2(module.exports);␊ + function requireCircular () {␊ + if (hasRequiredCircular) return circular;␊ + hasRequiredCircular = 1;␊ + const lib = requireCustomModule();␊ ␊ - });␊ + circular.extend1 = function (exports) {␊ + exports.get2 = function () {␊ + return 'indirect ref';␊ + };␊ + };␊ ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module/lib/circular.js", function (module, exports) {␊ - const lib = commonjsRequire("../", "/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module/lib");␊ + circular.extend2 = function (exports) {␊ + exports.get3 = lib.get1;␊ + };␊ + return circular;␊ + }␊ ␊ - module.exports.extend1 = function (exports) {␊ - exports.get2 = function () {␊ - return 'indirect ref';␊ - };␊ - };␊ + var hasRequiredCustomModule;␊ ␊ - module.exports.extend2 = function (exports) {␊ - exports.get3 = lib.get1;␊ - };␊ + function requireCustomModule () {␊ + if (hasRequiredCustomModule) return customModule.exports;␊ + hasRequiredCustomModule = 1;␊ + (function (module) {␊ + const circular = requireCircular();␊ ␊ - });␊ + circular.extend1(module.exports);␊ + ␊ + customModule.exports.get1 = function () {␊ + return 'all good';␊ + };␊ ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module/index.js");␊ + circular.extend2(module.exports);␊ + }(customModule));␊ + return customModule.exports;␊ + }␊ + ␊ + var main = {};␊ ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - const custom = commonjsRequire("custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-root-circular");␊ + const custom = requireCustomModule();␊ ␊ t.is(custom.get1(), 'all good');␊ t.is(custom.get2(), 'indirect ref');␊ @@ -4243,109 +2505,94 @@ Generated by [AVA](https://avajs.dev). `, } -## dynamic-require-targets-fallback +## dynamic-require-slash-access > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var dynamicRequireSlashAccess;␊ + var hasRequiredDynamicRequireSlashAccess;␊ ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function requireDynamicRequireSlashAccess () {␊ + if (hasRequiredDynamicRequireSlashAccess) return dynamicRequireSlashAccess;␊ + hasRequiredDynamicRequireSlashAccess = 1;␊ + dynamicRequireSlashAccess = 'same-directory';␊ + return dynamicRequireSlashAccess;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + var sub$2;␊ + var hasRequiredSub$1;␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + function requireSub$1 () {␊ + if (hasRequiredSub$1) return sub$2;␊ + hasRequiredSub$1 = 1;␊ + sub$2 = 'sub';␊ + return sub$2;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var sub$1;␊ + var hasRequiredSub;␊ ␊ - return joined;␊ + function requireSub () {␊ + if (hasRequiredSub) return sub$1;␊ + hasRequiredSub = 1;␊ + sub$1 = 'sub';␊ + return sub$1;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ + var customModule;␊ + var hasRequiredCustomModule;␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + function requireCustomModule () {␊ + if (hasRequiredCustomModule) return customModule;␊ + hasRequiredCustomModule = 1;␊ + customModule = 'custom-module' + ' + ' + requireSub();␊ + return customModule;␊ + }␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + var dynamicModules;␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-slash-access": requireDynamicRequireSlashAccess,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-slash-access/index.js": requireDynamicRequireSlashAccess,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-slash-access/sub": requireSub$1,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-slash-access/sub/index.js": requireSub$1,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-slash-access/node_modules/custom-module": requireCustomModule,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-slash-access/node_modules/custom-module/index.js": requireCustomModule,␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-slash-access/node_modules/custom-module2/sub.js": requireSub␊ + });␊ + }␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + 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.');␊ + }␊ ␊ - return '.';␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + commonjsRequire.resolve = commonjsResolve;␊ + ␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -4359,15 +2606,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -4379,98 +2620,177 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - return require(path);␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function join () {␊ + if (arguments.length === 0) return '.';␊ + var joined;␊ + for (var i = 0; i < arguments.length; ++i) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ + if (joined === undefined)␊ + joined = arg;␊ + else␊ + joined += '/' + arg;␊ + }␊ + }␊ + if (joined === undefined) return '.';␊ + return joined;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-targets-fallback/dep1.js", function (module, exports) {␊ - module.exports = 'dep';␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + function takeModule$1(name) {␊ + return commonjsRequire(name, "/$$rollup_base$$/fixtures/function/dynamic-require-slash-access/sub");␊ + }␊ ␊ - });␊ + var sub = {␊ + parent: takeModule$1('..'),␊ + customModule: takeModule$1('custom-module')␊ + };␊ ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - function takeModule(withName) {␊ - return commonjsRequire(withName,"/$$rollup_base$$/fixtures/function/dynamic-require-targets-fallback");␊ + function takeModule(name) {␊ + return commonjsRequire(name, "/$$rollup_base$$/fixtures/function/dynamic-require-slash-access");␊ }␊ ␊ - t.is(takeModule('./dep1.js'), 'dep');␊ - // The bundled code will run from test/helpers/util.js␊ - t.is(takeModule('../fixtures/function/dynamic-require-targets-fallback/dep2.js'), 'dep');␊ + t.is(takeModule('.'), 'same-directory', '.');␊ + t.is(takeModule('./'), 'same-directory', './');␊ + t.is(takeModule('.//'), 'same-directory', './/');␊ + ␊ + t.is(takeModule('./sub'), 'sub', './sub');␊ + ␊ + t.is(takeModule('custom-module'), 'custom-module + sub', 'custom-module');␊ + t.deepEqual(sub, {␊ + parent: 'same-directory',␊ + customModule: 'custom-module + sub'␊ + });␊ ␊ module.exports = main;␊ `, } -## dynamic-require-targets-no-fallback +## dynamic-require-targets-fallback > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var dep1;␊ + var hasRequiredDep1;␊ + ␊ + function requireDep1 () {␊ + if (hasRequiredDep1) return dep1;␊ + hasRequiredDep1 = 1;␊ + dep1 = 'dep';␊ + return dep1;␊ + }␊ + ␊ + var dynamicModules;␊ + ␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-targets-fallback/dep1.js": requireDep1␊ + });␊ + }␊ + ␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + return require(path);␊ + }␊ + ␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + }␊ + ␊ + commonjsRequire.resolve = commonjsResolve;␊ + ␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ + var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ + path = normalize(path);␊ + var relPath;␊ + if (path[0] === '/') {␊ + originalModuleDir = '/';␊ + }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ + while (true) {␊ + if (!shouldTryNodeModules) {␊ + relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ + } else if (originalModuleDir) {␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + } else {␊ + relPath = normalize(join('node_modules', path));␊ + }␊ + ␊ + if (relPath.endsWith('/..')) {␊ + break; // Travelled too far up, avoid infinite loop␊ + }␊ ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ + return resolvedPath;␊ + }␊ + }␊ + if (!shouldTryNodeModules) break;␊ + var nextDir = normalize(originalModuleDir + '/..');␊ + if (nextDir === originalModuleDir) break;␊ + originalModuleDir = nextDir;␊ + }␊ + return null;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ + }␊ ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ @@ -4489,71 +2809,95 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ + if (arguments.length === 0) return '.';␊ var joined;␊ for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ if (joined === undefined)␊ - joined = arg;␊ + joined = arg;␊ else␊ - joined += '/' + arg;␊ - }␊ + joined += '/' + arg;␊ + }␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ + if (joined === undefined) return '.';␊ return joined;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + var main = {};␊ + ␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + function takeModule(withName) {␊ + return commonjsRequire(withName, "/$$rollup_base$$/fixtures/function/dynamic-require-targets-fallback");␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + t.is(takeModule('./dep1.js'), 'dep');␊ + // The bundled code will run from test/helpers/util.js␊ + t.is(takeModule('../fixtures/function/dynamic-require-targets-fallback/dep2.js'), 'dep');␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + module.exports = main;␊ + `, + } + +## dynamic-require-targets-no-fallback + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var dep1;␊ + var hasRequiredDep1;␊ + ␊ + function requireDep1 () {␊ + if (hasRequiredDep1) return dep1;␊ + hasRequiredDep1 = 1;␊ + dep1 = 'dep';␊ + return dep1;␊ + }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var dynamicModules;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/$$rollup_base$$/fixtures/function/dynamic-require-targets-no-fallback/dep1.js": requireDep1␊ + });␊ + }␊ + ␊ + function commonjsRequire(path, originalModuleDir) {␊ + var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + 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.');␊ + }␊ ␊ - return '.';␊ + function commonjsResolve (path, originalModuleDir) {␊ + const resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + commonjsRequire.resolve = commonjsResolve;␊ + ␊ + function commonjsResolveImpl (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ originalModuleDir = '/';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ @@ -4567,15 +2911,9 @@ Generated by [AVA](https://avajs.dev). break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -4587,68 +2925,60 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - 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.');␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function join () {␊ + if (arguments.length === 0) return '.';␊ + var joined;␊ + for (var i = 0; i < arguments.length; ++i) {␊ + var arg = arguments[i];␊ + if (arg.length > 0) {␊ + if (joined === undefined)␊ + joined = arg;␊ + else␊ + joined += '/' + arg;␊ + }␊ + }␊ + if (joined === undefined) return '.';␊ + return joined;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-targets-no-fallback/dep1.js", function (module, exports) {␊ - module.exports = 'dep';␊ - ␊ - });␊ - ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule(withName) {␊ - return commonjsRequire(withName,"/$$rollup_base$$/fixtures/function/dynamic-require-targets-no-fallback");␊ + return commonjsRequire(withName, "/$$rollup_base$$/fixtures/function/dynamic-require-targets-no-fallback");␊ }␊ ␊ t.is(takeModule('./dep1.js'), 'dep');␊ @@ -5522,20 +3852,20 @@ Generated by [AVA](https://avajs.dev). ␊ var main$1 = {};␊ ␊ - var require$$0$1 = 'other.js';␊ + var require$$0 = 'other.js';␊ ␊ - var require$$1 = 'both.js';␊ + var require$$2 = 'both.js';␊ ␊ - const other = require$$0$1;␊ - const both$1 = require$$1;␊ + const other = require$$0;␊ + const both$1 = require$$2;␊ ␊ t.deepEqual(other, 'other.js', 'other other');␊ t.deepEqual(both$1, 'both.js', 'other both');␊ ␊ - var require$$0 = 'main.js';␊ + var require$$1 = 'main.js';␊ ␊ - const main = require$$0;␊ - const both = require$$1;␊ + const main = require$$1;␊ + const both = require$$2;␊ ␊ t.deepEqual(main, 'main.js', 'main main');␊ t.deepEqual(both, 'both.js', 'main both');␊ @@ -6201,6 +4531,27 @@ Generated by [AVA](https://avajs.dev). `, } +## module-meta-properties + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var dep$1 = {};␊ + ␊ + dep$1.foo = 'foo';␊ + ␊ + const dep = dep$1;␊ + ␊ + t.is(dep.foo, 'foo');␊ + ␊ + module.exports = main;␊ + `, + } + ## module_require > Snapshot 1 @@ -6465,50 +4816,6 @@ Generated by [AVA](https://avajs.dev). `, } -## no-default-export-live-binding - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var dep1 = {␊ - foo: 'foo',␊ - update: () => (dep1 = { foo: 'bar' })␊ - };␊ - ␊ - var dep1$1 = dep1;␊ - ␊ - var dep2$1 = {exports: {}};␊ - ␊ - dep2$1.exports.foo = 'foo';␊ - dep2$1.exports.update = () => (dep2$1.exports = { foo: 'bar' });␊ - ␊ - var dep2 = dep2$1.exports;␊ - ␊ - var dep3$1 = {exports: {}};␊ - ␊ - (function (module, exports) {␊ - exports.foo = 'foo';␊ - module.exports.update = () => (module.exports = { foo: 'bar' });␊ - }(dep3$1, dep3$1.exports));␊ - ␊ - var dep3 = dep3$1.exports;␊ - ␊ - t.is(dep1$1.foo, 'foo', 'dep1');␊ - dep1$1.update();␊ - t.is(dep1$1.foo, 'foo', 'dep1 updated');␊ - ␊ - t.is(dep2.foo, 'foo', 'dep2');␊ - dep2.update();␊ - t.is(dep2.foo, 'foo', 'dep2 updated');␊ - ␊ - t.is(dep3.foo, 'foo', 'dep3');␊ - dep3.update();␊ - t.is(dep3.foo, 'foo', 'dep3 updated');␊ - `, - } - ## no-exports-entry > Snapshot 1 @@ -6535,7 +4842,7 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var main$1 = {};␊ + var main = {};␊ ␊ var dep$1 = {};␊ ␊ @@ -6545,8 +4852,6 @@ Generated by [AVA](https://avajs.dev). ␊ t.is(dep.foo, 'bar');␊ ␊ - var main = main$1;␊ - ␊ module.exports = main;␊ `, } @@ -6768,10 +5073,10 @@ Generated by [AVA](https://avajs.dev). const arrayPattern = arrayPattern$1.exports;␊ const assignmentPattern = assignmentPattern$1.exports;␊ ␊ - t.deepEqual(identifier, {});␊ - t.deepEqual(property, {});␊ - t.deepEqual(arrayPattern, {});␊ - t.deepEqual(assignmentPattern, {});␊ + t.deepEqual(identifier, {}, 'identifier');␊ + t.deepEqual(property, {}, 'property');␊ + t.deepEqual(arrayPattern, {}, 'arrayPattern');␊ + t.deepEqual(assignmentPattern, {}, 'assignmentPattern');␊ ␊ module.exports = main;␊ `, @@ -7094,6 +5399,29 @@ Generated by [AVA](https://avajs.dev). `, } +## shorthand-require + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + function commonjsRequire(path) {␊ + 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.');␊ + }␊ + ␊ + const HOST = {␊ + require: commonjsRequire␊ + };␊ + ␊ + var main = {␊ + HOST␊ + };␊ + ␊ + module.exports = main;␊ + `, + } + ## skips-dead-branches > Snapshot 1 @@ -7114,6 +5442,78 @@ Generated by [AVA](https://avajs.dev). `, } +## strict-require-semantic-exportmode-exports + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + ␊ + var main = {};␊ + ␊ + var assignExports = {};␊ + ␊ + var hasRequiredAssignExports;␊ + ␊ + function requireAssignExports () {␊ + if (hasRequiredAssignExports) return assignExports;␊ + hasRequiredAssignExports = 1;␊ + assignExports.foo = 'foo';␊ + commonjsGlobal.hasAssignExportsRun = true;␊ + return assignExports;␊ + }␊ + ␊ + var reassignModuleExports = {exports: {}};␊ + ␊ + var hasRequiredReassignModuleExports;␊ + ␊ + function requireReassignModuleExports () {␊ + if (hasRequiredReassignModuleExports) return reassignModuleExports.exports;␊ + hasRequiredReassignModuleExports = 1;␊ + reassignModuleExports.exports = { bar: 'bar' };␊ + reassignModuleExports.exports.foo = 'foo';␊ + commonjsGlobal.hasReassignModuleExportsRun = true;␊ + return reassignModuleExports.exports;␊ + }␊ + ␊ + var compiledEsm = {};␊ + ␊ + var hasRequiredCompiledEsm;␊ + ␊ + function requireCompiledEsm () {␊ + if (hasRequiredCompiledEsm) return compiledEsm;␊ + hasRequiredCompiledEsm = 1;␊ + compiledEsm.__esModule = true;␊ + Object.defineProperty(compiledEsm, '__esModule', { value: true });␊ + compiledEsm.foo = 'foo';␊ + commonjsGlobal.hasCompiledEsmRun = true;␊ + return compiledEsm;␊ + }␊ + ␊ + t.is(commonjsGlobal.hasAssignExportsRun, undefined, 'before require');␊ + t.is(requireAssignExports().foo, 'foo');␊ + ␊ + t.is(commonjsGlobal.hasAssignExportsRun, true, 'after require');␊ + delete commonjsGlobal.hasAssignExportsRun;␊ + ␊ + t.is(commonjsGlobal.hasReassignModuleExportsRun, undefined, 'before require');␊ + t.is(requireReassignModuleExports().foo, 'foo');␊ + ␊ + t.is(commonjsGlobal.hasReassignModuleExportsRun, true, 'after require');␊ + delete commonjsGlobal.hasReassignModuleExportsRun;␊ + ␊ + t.is(commonjsGlobal.hasCompiledEsmRun, undefined, 'before require');␊ + t.is(requireCompiledEsm().foo, 'foo');␊ + ␊ + t.is(commonjsGlobal.hasCompiledEsmRun, true, 'after require');␊ + delete commonjsGlobal.hasCompiledEsmRun;␊ + ␊ + module.exports = main;␊ + `, + } + ## this > Snapshot 1 @@ -7840,6 +6240,8 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ + var main = {};␊ + ␊ /* eslint-disable global-require */␊ ␊ try {␊ @@ -7847,6 +6249,8 @@ Generated by [AVA](https://avajs.dev). } catch (ignored) {␊ /* ignore */␊ }␊ + ␊ + module.exports = main;␊ `, } @@ -7857,6 +6261,8 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ + var main = {};␊ + ␊ /* eslint-disable global-require */␊ ␊ try {␊ @@ -7864,6 +6270,8 @@ Generated by [AVA](https://avajs.dev). } catch (ignored) {␊ /* ignore */␊ }␊ + ␊ + module.exports = main;␊ `, } @@ -7874,6 +6282,8 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ + var main = {};␊ + ␊ /* eslint-disable global-require */␊ ␊ try {␊ @@ -7881,6 +6291,8 @@ Generated by [AVA](https://avajs.dev). } catch (ignored) {␊ /* ignore */␊ }␊ + ␊ + module.exports = main;␊ `, } @@ -7891,21 +6303,19 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - function commonjsRequire (path) {␊ + function commonjsRequire(path) {␊ 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.');␊ }␊ ␊ - var foo$1 = {exports: {}};␊ + var foo = {exports: {}};␊ ␊ if (typeof commonjsRequire === 'function' && commonjsRequire) {␊ - foo$1.exports = 1;␊ + foo.exports = 'require detected';␊ } else {␊ - foo$1.exports = 2;␊ + foo.exports = 'could not detect require';␊ }␊ ␊ - var foo = foo$1.exports;␊ - ␊ - t.is(foo, 1);␊ + t.is(foo.exports, 'require detected');␊ `, } @@ -7916,21 +6326,19 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - function commonjsRequire (path) {␊ + function commonjsRequire(path) {␊ 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.');␊ }␊ ␊ - var foo$1 = {exports: {}};␊ + var foo = {exports: {}};␊ ␊ if (typeof commonjsRequire === 'function' && commonjsRequire) {␊ - foo$1.exports = 1;␊ + foo.exports = 1;␊ } else {␊ - foo$1.exports = 2;␊ + foo.exports = 2;␊ }␊ ␊ - var foo = foo$1.exports;␊ - ␊ - t.is(foo, 1);␊ + t.is(foo.exports, 1);␊ `, } @@ -7956,24 +6364,3 @@ Generated by [AVA](https://avajs.dev). module.exports = main;␊ `, } - -## module-meta-properties - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var main = {};␊ - ␊ - var dep$1 = {};␊ - ␊ - dep$1.foo = 'foo';␊ - ␊ - const dep = dep$1;␊ - ␊ - t.is(dep.foo, 'foo');␊ - ␊ - module.exports = main;␊ - `, - } diff --git a/packages/commonjs/test/snapshots/function.js.snap b/packages/commonjs/test/snapshots/function.js.snap index 0a4924df3..7a81a3203 100644 Binary files a/packages/commonjs/test/snapshots/function.js.snap and b/packages/commonjs/test/snapshots/function.js.snap differ diff --git a/packages/commonjs/test/snapshots/test.js.md b/packages/commonjs/test/snapshots/test.js.md index 507b22d70..a86b22dab 100644 --- a/packages/commonjs/test/snapshots/test.js.md +++ b/packages/commonjs/test/snapshots/test.js.md @@ -94,22 +94,3 @@ Generated by [AVA](https://avajs.dev). ␊ module.exports = main;␊ ` - -## imports .cjs file extension by default - -> Snapshot 1 - - `'use strict';␊ - ␊ - var main = {};␊ - ␊ - var _export = {␊ - test: 42␊ - };␊ - ␊ - const { test } = _export;␊ - ␊ - console.log(test);␊ - ␊ - module.exports = main;␊ - ` diff --git a/packages/commonjs/test/snapshots/test.js.snap b/packages/commonjs/test/snapshots/test.js.snap index 7289e9012..4ae913ba5 100644 Binary files a/packages/commonjs/test/snapshots/test.js.snap and b/packages/commonjs/test/snapshots/test.js.snap differ diff --git a/packages/commonjs/test/test.js b/packages/commonjs/test/test.js index c2413d3c1..7a6405a33 100644 --- a/packages/commonjs/test/test.js +++ b/packages/commonjs/test/test.js @@ -619,79 +619,6 @@ test('logs a warning when the deprecated namedExports option is used', async (t) ); }); -test('imports .cjs file extension by default', async (t) => { - const bundle = await rollup({ - input: 'fixtures/samples/cjs-extension/main.js', - plugins: [commonjs()] - }); - t.snapshot(await getCodeFromBundle(bundle)); -}); - -test('registers dynamic requires when entry is from a different loader', async (t) => { - const bundle = await rollup({ - input: 'fixtures/samples/dynamic-require-different-loader/main.js', - plugins: [ - { - load(id) { - if (id === path.resolve('fixtures/samples/dynamic-require-different-loader/main.js')) { - return 'import submodule1 from "./submodule1"; export default submodule1();'; - } - return null; - } - }, - commonjs({ - dynamicRequireTargets: ['fixtures/samples/dynamic-require-different-loader/submodule2.js'], - transformMixedEsModules: true - }) - ] - }); - - t.is((await executeBundle(bundle, t)).exports, 'Hello there'); -}); - -test('transforms the es file with a `commonjsRequire` and no `require`s', async (t) => { - const bundle = await rollup({ - input: 'fixtures/samples/dynamic-require-es-mixed-helpers/main.js', - plugins: [ - commonjs({ - dynamicRequireTargets: ['fixtures/samples/dynamic-require-es-mixed-helpers/submodule.js'], - transformMixedEsModules: true - }) - ] - }); - - const code = await getCodeFromBundle(bundle); - - t.is(/commonjsRequire\(["']\.\/submodule\.js/.test(code), true); -}); - -test('does not wrap commonjsRegister calls in createCommonjsModule', async (t) => { - const bundle = await rollup({ - input: 'fixtures/samples/dynamic-require-double-wrap/main.js', - plugins: [ - commonjs({ - sourceMap: true, - dynamicRequireTargets: ['fixtures/samples/dynamic-require-double-wrap/submodule.js'] - }) - ] - }); - - const code = await getCodeFromBundle(bundle, { exports: 'named' }); - - t.not(/createCommonjsModule\(function/.test(code), true); -}); - -test('does not replace shorthand `require` property in object', async (t) => { - const bundle = await rollup({ - input: 'fixtures/samples/shorthand-require/main.js', - plugins: [commonjs()] - }); - - const code = await getCodeFromBundle(bundle, { exports: 'named' }); - - t.is(/require: commonjsRequire/.test(code), true); -}); - // This test uses worker threads to simulate an empty internal cache and needs at least Node 12 if (Number(/^v(\d+)/.exec(process.version)[1]) >= 12) { test('can be cached across instances', async (t) => {