convert @babel/preset-env to typescript (#13217)

* babel-preset-env flowts rename

* babel-preset-env flowts convert

* babel-preset-env fixes

* babel-preset-env

* make generate-tsconfig

* Minimize diff

* Fix many type errors

Co-authored-by: Nicolò Ribaudo <nicolo.ribaudo@gmail.com>
This commit is contained in:
Bogdan Savluk 2021-06-22 16:58:08 +02:00 committed by GitHub
parent 22e5afc2f3
commit 47ad54a057
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 117 additions and 124 deletions

View File

@ -1,4 +1,3 @@
// @flow
/* eslint sort-keys: "error" */ /* eslint sort-keys: "error" */
import syntaxAsyncGenerators from "@babel/plugin-syntax-async-generators"; import syntaxAsyncGenerators from "@babel/plugin-syntax-async-generators";

View File

@ -1,9 +1,6 @@
// @flow import { getInclusionReasons } from "@babel/helper-compilation-targets";
import { import type { Targets } from "@babel/helper-compilation-targets";
getInclusionReasons,
type Targets,
} from "@babel/helper-compilation-targets";
// Outputs a message that shows which target(s) caused an item to be included: // Outputs a message that shows which target(s) caused an item to be included:
// transform-foo { "edge":"13", "firefox":"49", "ie":"10" } // transform-foo { "edge":"13", "firefox":"49", "ie":"10" }

View File

@ -1,5 +1,3 @@
// @flow
import { lt } from "semver"; import { lt } from "semver";
import { minVersions } from "./available-plugins"; import { minVersions } from "./available-plugins";

View File

@ -1,5 +1,3 @@
// @flow
const defaultExcludesForLooseMode = ["transform-typeof-symbol"]; const defaultExcludesForLooseMode = ["transform-typeof-symbol"];
export default function ({ loose }: { loose: boolean }): null | string[] { export default function ({ loose }: { loose: boolean }): null | string[] {

View File

@ -1,6 +1,5 @@
//@flow import { lt } from "semver";
import type { SemVer } from "semver";
import { SemVer, lt } from "semver";
import { logPlugin } from "./debug"; import { logPlugin } from "./debug";
import getOptionSpecificExcludesFor from "./get-option-specific-excludes"; import getOptionSpecificExcludesFor from "./get-option-specific-excludes";
import { removeUnnecessaryItems, removeUnsupportedItems } from "./filter-items"; import { removeUnnecessaryItems, removeUnsupportedItems } from "./filter-items";
@ -27,13 +26,13 @@ import getTargets, {
prettifyTargets, prettifyTargets,
filterItems, filterItems,
isRequired, isRequired,
type Targets,
type InputTargets,
} from "@babel/helper-compilation-targets"; } from "@babel/helper-compilation-targets";
import type { Targets, InputTargets } from "@babel/helper-compilation-targets";
import availablePlugins from "./available-plugins"; import availablePlugins from "./available-plugins";
import { declare } from "@babel/helper-plugin-utils"; import { declare } from "@babel/helper-plugin-utils";
import typeof ModuleTransformationsType from "./module-transformations"; type ModuleTransformationsType =
typeof import("./module-transformations").default;
import type { BuiltInsOption, ModuleOption } from "./types"; import type { BuiltInsOption, ModuleOption } from "./types";
// TODO: Remove in Babel 8 // TODO: Remove in Babel 8
@ -92,7 +91,7 @@ const getPlugin = (pluginName: string) => {
return plugin; return plugin;
}; };
export const transformIncludesAndExcludes = (opts: Array<string>): Object => { export const transformIncludesAndExcludes = (opts: Array<string>): any => {
return opts.reduce( return opts.reduce(
(result, opt) => { (result, opt) => {
const target = opt.match(/^(es|es6|es7|esnext|web)\./) const target = opt.match(/^(es|es6|es7|esnext|web)\./)
@ -116,14 +115,14 @@ export const getModulesPluginNames = ({
shouldTransformDynamicImport, shouldTransformDynamicImport,
shouldTransformExportNamespaceFrom, shouldTransformExportNamespaceFrom,
shouldParseTopLevelAwait, shouldParseTopLevelAwait,
}: {| }: {
modules: ModuleOption, modules: ModuleOption;
transformations: ModuleTransformationsType, transformations: ModuleTransformationsType;
shouldTransformESM: boolean, shouldTransformESM: boolean;
shouldTransformDynamicImport: boolean, shouldTransformDynamicImport: boolean;
shouldTransformExportNamespaceFrom: boolean, shouldTransformExportNamespaceFrom: boolean;
shouldParseTopLevelAwait: boolean, shouldParseTopLevelAwait: boolean;
|}) => { }) => {
const modulesPluginNames = []; const modulesPluginNames = [];
if (modules !== false && transformations[modules]) { if (modules !== false && transformations[modules]) {
if (shouldTransformESM) { if (shouldTransformESM) {
@ -173,15 +172,15 @@ export const getPolyfillPlugins = ({
regenerator, regenerator,
debug, debug,
}: { }: {
useBuiltIns: BuiltInsOption, useBuiltIns: BuiltInsOption;
corejs: typeof SemVer | null | false, corejs: SemVer | null | false;
polyfillTargets: Targets, polyfillTargets: Targets;
include: Set<string>, include: Set<string>;
exclude: Set<string>, exclude: Set<string>;
proposals: boolean, proposals: boolean;
shippedProposals: boolean, shippedProposals: boolean;
regenerator: boolean, regenerator: boolean;
debug: boolean, debug: boolean;
}) => { }) => {
const polyfillPlugins = []; const polyfillPlugins = [];
if (useBuiltIns === "usage" || useBuiltIns === "entry") { if (useBuiltIns === "usage" || useBuiltIns === "entry") {
@ -249,7 +248,7 @@ function getLocalTargets(
`); `);
} }
return getTargets((optionsTargets: InputTargets), { return getTargets(optionsTargets as InputTargets, {
ignoreBrowserslistConfig, ignoreBrowserslistConfig,
configPath, configPath,
browserslistEnv, browserslistEnv,

View File

@ -1,12 +1,10 @@
// @flow type AvailablePlugins = typeof import("./available-plugins").default;
import typeof AvailablePlugins from "./available-plugins"; export default {
export default ({
auto: "transform-modules-commonjs", auto: "transform-modules-commonjs",
amd: "transform-modules-amd", amd: "transform-modules-amd",
commonjs: "transform-modules-commonjs", commonjs: "transform-modules-commonjs",
cjs: "transform-modules-commonjs", cjs: "transform-modules-commonjs",
systemjs: "transform-modules-systemjs", systemjs: "transform-modules-systemjs",
umd: "transform-modules-umd", umd: "transform-modules-umd",
}: { [transform: string]: $Keys<AvailablePlugins> }); } as { [transform: string]: keyof AvailablePlugins };

View File

@ -1,6 +1,6 @@
// @flow
import corejs3Polyfills from "core-js-compat/data.json"; import corejs3Polyfills from "core-js-compat/data.json";
import { coerce, SemVer } from "semver"; import { coerce } from "semver";
import type { SemVer } from "semver";
import corejs2Polyfills from "@babel/compat-data/corejs2-built-ins"; import corejs2Polyfills from "@babel/compat-data/corejs2-built-ins";
import { plugins as pluginsList } from "./plugins-compat-data"; import { plugins as pluginsList } from "./plugins-compat-data";
import moduleTransformations from "./module-transformations"; import moduleTransformations from "./module-transformations";
@ -22,6 +22,8 @@ import type {
PluginListOption, PluginListOption,
} from "./types"; } from "./types";
declare const PACKAGE_JSON: { name: string; version: string };
const v = new OptionValidator(PACKAGE_JSON.name); const v = new OptionValidator(PACKAGE_JSON.name);
const allPluginsList = Object.keys(pluginsList); const allPluginsList = Object.keys(pluginsList);
@ -111,9 +113,10 @@ export const checkDuplicateIncludeExcludes = (
); );
}; };
const normalizeTargets = (targets): $PropertyType<Options, "targets"> => { const normalizeTargets = (targets): Options["targets"] => {
// TODO: Allow to use only query or strings as a targets from next breaking change. // TODO: Allow to use only query or strings as a targets from next breaking change.
if (typeof targets === "string" || Array.isArray(targets)) { if (typeof targets === "string" || Array.isArray(targets)) {
// @ts-expect-error
return { browsers: targets }; return { browsers: targets };
} }
return { ...targets }; return { ...targets };
@ -150,12 +153,12 @@ export const validateUseBuiltInsOption = (
}; };
export type NormalizedCorejsOption = { export type NormalizedCorejsOption = {
proposals: boolean, proposals: boolean;
version: typeof SemVer | null | false, version: SemVer | null | false;
}; };
export function normalizeCoreJSOption( export function normalizeCoreJSOption(
corejs?: CorejsOption, corejs: CorejsOption | undefined | null,
useBuiltIns: BuiltInsOption, useBuiltIns: BuiltInsOption,
): NormalizedCorejsOption { ): NormalizedCorejsOption {
let proposals = false; let proposals = false;
@ -249,7 +252,7 @@ export default function normalizeOptions(opts: Options) {
opts.ignoreBrowserslistConfig, opts.ignoreBrowserslistConfig,
false, false,
), ),
loose: v.validateBooleanOption(TopLevelOptions.loose, opts.loose), loose: v.validateBooleanOption<boolean>(TopLevelOptions.loose, opts.loose),
modules: validateModulesOption(opts.modules), modules: validateModulesOption(opts.modules),
shippedProposals: v.validateBooleanOption( shippedProposals: v.validateBooleanOption(
TopLevelOptions.shippedProposals, TopLevelOptions.shippedProposals,

View File

@ -1,5 +1,3 @@
// @flow
export const TopLevelOptions = { export const TopLevelOptions = {
bugfixes: "bugfixes", bugfixes: "bugfixes",
configPath: "configPath", configPath: "configPath",
@ -16,7 +14,7 @@ export const TopLevelOptions = {
targets: "targets", targets: "targets",
useBuiltIns: "useBuiltIns", useBuiltIns: "useBuiltIns",
browserslistEnv: "browserslistEnv", browserslistEnv: "browserslistEnv",
}; } as const;
export const ModulesOption = { export const ModulesOption = {
false: false, false: false,
@ -26,10 +24,10 @@ export const ModulesOption = {
cjs: "cjs", cjs: "cjs",
systemjs: "systemjs", systemjs: "systemjs",
umd: "umd", umd: "umd",
}; } as const;
export const UseBuiltInsOption = { export const UseBuiltInsOption = {
false: false, false: false,
entry: "entry", entry: "entry",
usage: "usage", usage: "usage",
}; } as const;

View File

@ -1,5 +1,3 @@
// @flow
import plugins from "@babel/compat-data/plugins"; import plugins from "@babel/compat-data/plugins";
import bugfixPlugins from "@babel/compat-data/plugin-bugfixes"; import bugfixPlugins from "@babel/compat-data/plugin-bugfixes";
import availablePlugins from "./available-plugins"; import availablePlugins from "./available-plugins";

View File

@ -1,8 +1,7 @@
// @flow
import { getImportSource, getRequireSource, isPolyfillSource } from "./utils"; import { getImportSource, getRequireSource, isPolyfillSource } from "./utils";
import type { NodePath } from "@babel/traverse"; import type { NodePath } from "@babel/traverse";
import * as t from "@babel/types";
const BABEL_POLYFILL_DEPRECATION = ` const BABEL_POLYFILL_DEPRECATION = `
\`@babel/polyfill\` is deprecated. Please, use required parts of \`core-js\` \`@babel/polyfill\` is deprecated. Please, use required parts of \`core-js\`
@ -19,7 +18,7 @@ export default function (
return { return {
name: "preset-env/replace-babel-polyfill", name: "preset-env/replace-babel-polyfill",
visitor: { visitor: {
ImportDeclaration(path: NodePath) { ImportDeclaration(path: NodePath<t.ImportDeclaration>) {
const src = getImportSource(path); const src = getImportSource(path);
if (usage && isPolyfillSource(src)) { if (usage && isPolyfillSource(src)) {
// $FlowIgnore // $FlowIgnore
@ -40,7 +39,7 @@ export default function (
} }
} }
}, },
Program(path: NodePath) { Program(path: NodePath<t.Program>) {
path.get("body").forEach(bodyPath => { path.get("body").forEach(bodyPath => {
const src = getRequireSource(bodyPath); const src = getRequireSource(bodyPath);
if (usage && isPolyfillSource(src)) { if (usage && isPolyfillSource(src)) {

View File

@ -1,7 +1,5 @@
// @flow
import { getImportSource, getRequireSource } from "./utils"; import { getImportSource, getRequireSource } from "./utils";
import type { NodePath } from "@babel/traverse"; import type { Visitor } from "@babel/traverse";
function isRegeneratorSource(source) { function isRegeneratorSource(source) {
return ( return (
@ -11,14 +9,14 @@ function isRegeneratorSource(source) {
} }
export default function () { export default function () {
const visitor = { const visitor: Visitor<{ regeneratorImportExcluded: boolean }> = {
ImportDeclaration(path: NodePath) { ImportDeclaration(path) {
if (isRegeneratorSource(getImportSource(path))) { if (isRegeneratorSource(getImportSource(path))) {
this.regeneratorImportExcluded = true; this.regeneratorImportExcluded = true;
path.remove(); path.remove();
} }
}, },
Program(path: NodePath) { Program(path) {
path.get("body").forEach(bodyPath => { path.get("body").forEach(bodyPath => {
if (isRegeneratorSource(getRequireSource(bodyPath))) { if (isRegeneratorSource(getRequireSource(bodyPath))) {
this.regeneratorImportExcluded = true; this.regeneratorImportExcluded = true;

View File

@ -1,24 +1,24 @@
// @flow
import * as t from "@babel/types"; import * as t from "@babel/types";
import type { NodePath } from "@babel/traverse"; import type { NodePath } from "@babel/traverse";
export function getImportSource({ node }: NodePath) { export function getImportSource({ node }: NodePath<t.ImportDeclaration>) {
if (node.specifiers.length === 0) return node.source.value; if (node.specifiers.length === 0) return node.source.value;
} }
export function getRequireSource({ node }: NodePath) { export function getRequireSource({ node }: NodePath) {
if (!t.isExpressionStatement(node)) return; if (!t.isExpressionStatement(node)) return;
const { expression } = node; const { expression } = node;
const isRequire = if (
t.isCallExpression(expression) && t.isCallExpression(expression) &&
t.isIdentifier(expression.callee) && t.isIdentifier(expression.callee) &&
expression.callee.name === "require" && expression.callee.name === "require" &&
expression.arguments.length === 1 && expression.arguments.length === 1 &&
t.isStringLiteral(expression.arguments[0]); t.isStringLiteral(expression.arguments[0])
if (isRequire) return expression.arguments[0].value; ) {
return expression.arguments[0].value;
}
} }
export function isPolyfillSource(source: ?string): boolean { export function isPolyfillSource(source?: string | null): boolean {
return source === "@babel/polyfill" || source === "core-js"; return source === "@babel/polyfill" || source === "core-js";
} }

View File

@ -3,5 +3,4 @@
export { export {
default, default,
isBrowsersQueryValid, isBrowsersQueryValid,
semverMin,
} from "@babel/helper-compilation-targets"; } from "@babel/helper-compilation-targets";

View File

@ -1,52 +0,0 @@
//@flow
import { ModulesOption, UseBuiltInsOption } from "./options";
import type { NormalizedCorejsOption } from "./normalize-options";
import type { Targets, InputTargets } from "@babel/helper-compilation-targets";
// Options
// Use explicit modules to prevent typo errors.
export type ModuleOption = $Values<typeof ModulesOption>;
export type BuiltInsOption = $Values<typeof UseBuiltInsOption>;
type CorejsVersion = 2 | 3 | string;
export type CorejsOption =
| false
| CorejsVersion
| { version: CorejsVersion, proposals: boolean };
export type PluginListItem = string | RegExp;
export type PluginListOption = Array<PluginListItem>;
export type Options = {
bugfixes: boolean,
configPath: string,
corejs: CorejsOption,
debug: boolean,
exclude: PluginListOption,
forceAllTransforms: boolean,
ignoreBrowserslistConfig: boolean,
include: PluginListOption,
loose: boolean,
modules: ModuleOption,
shippedProposals: boolean,
spec: boolean,
targets: { ...InputTargets, uglify?: boolean, esmodules?: boolean },
useBuiltIns: BuiltInsOption,
browserslistEnv: string,
};
// Babel
export type Plugin = [Object, Object];
export type InternalPluginOptions = {
corejs: NormalizedCorejsOption,
include: Set<string>,
exclude: Set<string>,
polyfillTargets: Targets,
debug: boolean,
proposals: boolean,
shippedProposals: boolean,
regenerator: boolean,
};

View File

@ -0,0 +1,57 @@
import { ModulesOption, UseBuiltInsOption } from "./options";
import type { NormalizedCorejsOption } from "./normalize-options";
import type { Targets, InputTargets } from "@babel/helper-compilation-targets";
// Options
// Use explicit modules to prevent typo errors.
export type ModuleOption = typeof ModulesOption[keyof typeof ModulesOption];
export type BuiltInsOption =
typeof UseBuiltInsOption[keyof typeof UseBuiltInsOption];
type CorejsVersion = 2 | 3 | string;
export type CorejsOption =
| false
| CorejsVersion
| {
version: CorejsVersion;
proposals: boolean;
};
export type PluginListItem = string | RegExp;
export type PluginListOption = Array<PluginListItem>;
export type Options = {
bugfixes: boolean;
configPath: string;
corejs: CorejsOption;
debug: boolean;
exclude: PluginListOption;
forceAllTransforms: boolean;
ignoreBrowserslistConfig: boolean;
include: PluginListOption;
loose: boolean;
modules: ModuleOption;
shippedProposals: boolean;
spec: boolean;
targets: {
uglify?: boolean;
esmodules?: boolean;
} & InputTargets;
useBuiltIns: BuiltInsOption;
browserslistEnv: string;
};
// Babel
export type Plugin = [any, any];
export type InternalPluginOptions = {
corejs: NormalizedCorejsOption;
include: Set<string>;
exclude: Set<string>;
polyfillTargets: Targets;
debug: boolean;
proposals: boolean;
shippedProposals: boolean;
regenerator: boolean;
};

View File

@ -32,6 +32,7 @@
"./packages/babel-plugin-transform-react-jsx/src/**/*.ts", "./packages/babel-plugin-transform-react-jsx/src/**/*.ts",
"./packages/babel-plugin-transform-runtime/src/**/*.ts", "./packages/babel-plugin-transform-runtime/src/**/*.ts",
"./packages/babel-plugin-transform-typescript/src/**/*.ts", "./packages/babel-plugin-transform-typescript/src/**/*.ts",
"./packages/babel-preset-env/src/**/*.ts",
"./packages/babel-standalone/src/**/*.ts", "./packages/babel-standalone/src/**/*.ts",
"./packages/babel-template/src/**/*.ts", "./packages/babel-template/src/**/*.ts",
"./packages/babel-traverse/src/**/*.ts", "./packages/babel-traverse/src/**/*.ts",
@ -129,6 +130,9 @@
"@babel/plugin-transform-typescript": [ "@babel/plugin-transform-typescript": [
"./packages/babel-plugin-transform-typescript/src" "./packages/babel-plugin-transform-typescript/src"
], ],
"@babel/preset-env": [
"./packages/babel-preset-env/src"
],
"@babel/standalone": [ "@babel/standalone": [
"./packages/babel-standalone/src" "./packages/babel-standalone/src"
], ],