Skip to content

Commit

Permalink
Refactor handling of modules plugins in preset-env (#15988)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo authored Oct 20, 2023
1 parent 637ee78 commit c46f000
Show file tree
Hide file tree
Showing 25 changed files with 125 additions and 104 deletions.
11 changes: 8 additions & 3 deletions packages/babel-core/src/config/helpers/config-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,14 @@ type EnvFunction = {
(envVars: Array<string>): boolean;
};

type CallerFactory = (
extractor: (callerMetadata: CallerMetadata | undefined) => unknown,
) => SimpleType;
type CallerFactory = {
<T extends SimpleType>(
extractor: (callerMetadata: CallerMetadata | undefined) => T,
): T;
(
extractor: (callerMetadata: CallerMetadata | undefined) => unknown,
): SimpleType;
};
type TargetsFunction = () => Targets;
type AssumptionFunction = (name: AssumptionName) => boolean | undefined;

Expand Down
152 changes: 95 additions & 57 deletions packages/babel-preset-env/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ import type { Targets, InputTargets } from "@babel/helper-compilation-targets";
import availablePlugins from "./available-plugins.ts";
import { declarePreset } from "@babel/helper-plugin-utils";

type ModuleTransformationsType =
typeof import("./module-transformations").default;
import type { BuiltInsOption, ModuleOption, Options } from "./types.ts";

// TODO: Remove in Babel 8
Expand Down Expand Up @@ -117,55 +115,37 @@ export const transformIncludesAndExcludes = (opts: Array<string>): any => {
);
};

export const getModulesPluginNames = ({
modules,
transformations,
shouldTransformESM,
shouldTransformDynamicImport,
shouldTransformExportNamespaceFrom,
}: {
modules: ModuleOption;
transformations: ModuleTransformationsType;
shouldTransformESM: boolean;
shouldTransformDynamicImport: boolean;
shouldTransformExportNamespaceFrom: boolean;
}) => {
function getSpecialModulesPluginNames(
modules: Exclude<ModuleOption, "auto">,
shouldTransformDynamicImport: boolean,
) {
const modulesPluginNames = [];
if (modules !== false && transformations[modules]) {
if (shouldTransformESM) {
modulesPluginNames.push(transformations[modules]);
}

if (shouldTransformDynamicImport) {
if (shouldTransformESM && modules !== "umd") {
modulesPluginNames.push("transform-dynamic-import");
} else {
console.warn(
"Dynamic import can only be transformed when transforming ES" +
" modules to AMD, CommonJS or SystemJS.",
);
}
}
if (modules) {
modulesPluginNames.push(moduleTransformations[modules]);
}

if (shouldTransformExportNamespaceFrom) {
modulesPluginNames.push("transform-export-namespace-from");
if (shouldTransformDynamicImport) {
if (modules && modules !== "umd") {
modulesPluginNames.push("transform-dynamic-import");
} else {
console.warn(
"Dynamic import can only be transformed when transforming ES" +
" modules to AMD, CommonJS or SystemJS.",
);
}
}

if (!process.env.BABEL_8_BREAKING) {
// Enable module-related syntax plugins for older Babel versions
if (!shouldTransformDynamicImport) {
modulesPluginNames.push("syntax-dynamic-import");
}
if (!shouldTransformExportNamespaceFrom) {
modulesPluginNames.push("syntax-export-namespace-from");
}
modulesPluginNames.push("syntax-top-level-await");
modulesPluginNames.push("syntax-import-meta");
}

return modulesPluginNames;
};
}

const getCoreJSOptions = ({
useBuiltIns,
Expand Down Expand Up @@ -312,16 +292,19 @@ function getLocalTargets(
}

function supportsStaticESM(caller: CallerMetadata | undefined) {
// TODO(Babel 8): Fallback to true
// @ts-expect-error supportsStaticESM is not defined in CallerMetadata
return !!caller?.supportsStaticESM;
}

function supportsDynamicImport(caller: CallerMetadata | undefined) {
// TODO(Babel 8): Fallback to true
// @ts-expect-error supportsDynamicImport is not defined in CallerMetadata
return !!caller?.supportsDynamicImport;
}

function supportsExportNamespaceFrom(caller: CallerMetadata | undefined) {
// TODO(Babel 8): Fallback to null
// @ts-expect-error supportsExportNamespaceFrom is not defined in CallerMetadata
return !!caller?.supportsExportNamespaceFrom;
}
Expand All @@ -344,7 +327,7 @@ export default declarePreset((api, opts: Options) => {
ignoreBrowserslistConfig,
include: optionsInclude,
loose,
modules,
modules: optionsModules,
shippedProposals,
spec,
targets: optionsTargets,
Expand Down Expand Up @@ -402,31 +385,34 @@ option \`forceAllTransforms: true\` instead.
const exclude = transformIncludesAndExcludes(optionsExclude);

const compatData = getPluginList(shippedProposals, bugfixes);
const shouldSkipExportNamespaceFrom =
(modules === "auto" && api.caller?.(supportsExportNamespaceFrom)) ||
(modules === false &&
!isRequired("transform-export-namespace-from", transformTargets, {
compatData,
includes: include.plugins,
excludes: exclude.plugins,
}));
const modulesPluginNames = getModulesPluginNames({
modules,
transformations: moduleTransformations,
// TODO: Remove the 'api.caller' check eventually. Just here to prevent
// unnecessary breakage in the short term for users on older betas/RCs.
shouldTransformESM: modules !== "auto" || !api.caller?.(supportsStaticESM),
shouldTransformDynamicImport:
modules !== "auto" || !api.caller?.(supportsDynamicImport),
shouldTransformExportNamespaceFrom: !shouldSkipExportNamespaceFrom,
});
const modules =
optionsModules === "auto"
? api.caller(supportsStaticESM)
? false
: "commonjs"
: optionsModules;
const shouldTransformDynamicImport =
optionsModules === "auto" ? !api.caller(supportsDynamicImport) : !!modules;

// If the caller does not support export-namespace-from, we forcefully add
// the plugin to `includes`.
// TODO(Babel 8): stop doing this, similarly to how we don't do this for any
// other plugin. We can consider adding bundlers as targets in the future,
// but we should not have a one-off special case for this plugin.
if (
optionsModules === "auto" &&
!api.caller(supportsExportNamespaceFrom) &&
!exclude.plugins.has("transform-export-namespace-from")
) {
include.plugins.add("transform-export-namespace-from");
}

const pluginNames = filterItems(
compatData,
include.plugins,
exclude.plugins,
transformTargets,
modulesPluginNames,
getSpecialModulesPluginNames(modules, shouldTransformDynamicImport),
getOptionSpecificExcludesFor({ loose }),
pluginSyntaxMap,
);
Expand Down Expand Up @@ -500,7 +486,7 @@ option \`forceAllTransforms: true\` instead.
console.log("@babel/preset-env: `DEBUG` option");
console.log("\nUsing targets:");
console.log(JSON.stringify(prettifyTargets(targets), null, 2));
console.log(`\nUsing modules transform: ${modules.toString()}`);
console.log(`\nUsing modules transform: ${optionsModules.toString()}`);
console.log("\nUsing plugins:");
pluginNames.forEach(pluginName => {
logPlugin(pluginName, targets, compatData);
Expand All @@ -515,3 +501,55 @@ option \`forceAllTransforms: true\` instead.

return { plugins };
});

// TODO(Babel 8): This is only here for backward compatibility. Remove it.
export { getModulesPluginNamesBackwardCompat as getModulesPluginNames };
const getModulesPluginNamesBackwardCompat = ({
modules,
transformations,
shouldTransformESM,
shouldTransformDynamicImport,
shouldTransformExportNamespaceFrom,
}: {
modules: ModuleOption;
transformations: typeof import("./module-transformations").default;
shouldTransformESM: boolean;
shouldTransformDynamicImport: boolean;
shouldTransformExportNamespaceFrom: boolean;
}) => {
const modulesPluginNames = [];
if (modules !== false && transformations[modules]) {
if (shouldTransformESM) {
modulesPluginNames.push(transformations[modules]);
}

if (shouldTransformDynamicImport) {
if (shouldTransformESM && modules !== "umd") {
modulesPluginNames.push("transform-dynamic-import");
} else {
console.warn(
"Dynamic import can only be transformed when transforming ES" +
" modules to AMD, CommonJS or SystemJS.",
);
}
}
}

if (shouldTransformExportNamespaceFrom) {
modulesPluginNames.push("transform-export-namespace-from");
}

if (!process.env.BABEL_8_BREAKING) {
// Enable module-related syntax plugins for older Babel versions
if (!shouldTransformDynamicImport) {
modulesPluginNames.push("syntax-dynamic-import");
}
if (!shouldTransformExportNamespaceFrom) {
modulesPluginNames.push("syntax-export-namespace-from");
}
modulesPluginNames.push("syntax-top-level-await");
modulesPluginNames.push("syntax-import-meta");
}

return modulesPluginNames;
};
1 change: 0 additions & 1 deletion packages/babel-preset-env/src/module-transformations.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
type AvailablePlugins = typeof import("./available-plugins").default;

export default {
auto: "transform-modules-commonjs",
amd: "transform-modules-amd",
commonjs: "transform-modules-commonjs",
cjs: "transform-modules-commonjs",
Expand Down
1 change: 1 addition & 0 deletions packages/babel-preset-env/src/shipped-proposals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const pluginSyntaxObject = process.env.BABEL_8_BREAKING
"transform-async-generator-functions": "syntax-async-generators",
"transform-class-properties": "syntax-class-properties",
"transform-class-static-block": "syntax-class-static-block",
"transform-export-namespace-from": "syntax-export-namespace-from",
"transform-json-strings": "syntax-json-strings",
"transform-nullish-coalescing-operator":
"syntax-nullish-coalescing-operator",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ Using plugins:
syntax-optional-catch-binding
syntax-async-generators
syntax-object-rest-spread
transform-export-namespace-from { }
bugfix/transform-safari-id-destructuring-collision-in-function-expression { safari < 16.3 }
transform-modules-commonjs
transform-dynamic-import
transform-export-namespace-from { }
syntax-top-level-await
syntax-import-meta

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ Using plugins:
transform-parameters { safari < 16.3 }
syntax-async-generators
syntax-object-rest-spread
transform-export-namespace-from { }
transform-modules-commonjs
transform-dynamic-import
transform-export-namespace-from { }
syntax-top-level-await
syntax-import-meta

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ Using plugins:
syntax-optional-catch-binding
syntax-async-generators
syntax-object-rest-spread
transform-export-namespace-from { }
transform-modules-commonjs
transform-dynamic-import
transform-export-namespace-from { }
syntax-top-level-await
syntax-import-meta

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ Using plugins:
syntax-optional-catch-binding
syntax-async-generators
syntax-object-rest-spread
transform-export-namespace-from { }
bugfix/transform-v8-spread-parameters-in-optional-chaining { chrome < 91 }
transform-modules-commonjs
transform-dynamic-import
transform-export-namespace-from { }
syntax-top-level-await
syntax-import-meta

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Using plugins:
transform-unicode-regex { ios < 12, safari < 12 }
transform-block-scoping { ios < 11, safari < 11 }
transform-export-namespace-from { android < 72, chrome < 72, edge < 79, firefox < 80, ios < 14.5, opera < 60, safari < 14.1, samsung < 11.0 }
syntax-dynamic-import
syntax-top-level-await
syntax-import-meta
corejs2: `DEBUG` option
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Using plugins:
transform-unicode-regex { ios < 12, safari < 12 }
transform-block-scoping { ios < 11, safari < 11 }
transform-export-namespace-from { android < 72, chrome < 72, edge < 79, firefox < 80, ios < 14.5, opera < 60, safari < 14.1, samsung < 11.0 }
syntax-dynamic-import
syntax-top-level-await
syntax-import-meta
corejs3: `DEBUG` option
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ Using plugins:
transform-parameters { ios < 16.3, safari < 16.3 }
syntax-async-generators
syntax-object-rest-spread
transform-export-namespace-from { }
transform-modules-commonjs
transform-dynamic-import
transform-export-namespace-from { }
syntax-top-level-await
syntax-import-meta

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ Using plugins:
transform-parameters { ios < 16.3, safari < 16.3 }
syntax-async-generators
syntax-object-rest-spread
transform-export-namespace-from { }
transform-modules-commonjs
transform-dynamic-import
transform-export-namespace-from { }
syntax-top-level-await
syntax-import-meta

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ Using plugins:
syntax-optional-catch-binding
syntax-async-generators
syntax-object-rest-spread
transform-export-namespace-from { }
transform-modules-commonjs
transform-dynamic-import
transform-export-namespace-from { }
syntax-top-level-await
syntax-import-meta

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Using plugins:
transform-property-literals { }
transform-reserved-words { }
transform-export-namespace-from { chrome < 72 }
syntax-dynamic-import
syntax-top-level-await
syntax-import-meta
corejs2: `DEBUG` option
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Using plugins:
transform-property-literals { }
transform-reserved-words { }
transform-export-namespace-from { chrome < 72 }
syntax-dynamic-import
syntax-top-level-await
syntax-import-meta
corejs3: `DEBUG` option
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Using plugins:
transform-property-literals { }
transform-reserved-words { }
transform-export-namespace-from { chrome < 72 }
syntax-dynamic-import
syntax-top-level-await
syntax-import-meta
corejs2: `DEBUG` option
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ Using plugins:
syntax-optional-catch-binding
syntax-async-generators
syntax-object-rest-spread
transform-export-namespace-from { }
transform-modules-commonjs
transform-dynamic-import
transform-export-namespace-from { }
syntax-top-level-await
syntax-import-meta
syntax-import-attributes
Expand Down
Loading

0 comments on commit c46f000

Please sign in to comment.