Skip to content

Commit

Permalink
[babel 8] Other Babel 8 misc changes (#15576)
Browse files Browse the repository at this point in the history
Co-authored-by: Hu谩ng J霉nli脿ng <jlhwung@gmail.com>
Co-authored-by: liuxingbaoyu <30521560+liuxingbaoyu@users.noreply.github.com>
  • Loading branch information
3 people committed Apr 27, 2023
1 parent eb62275 commit c060e5e
Show file tree
Hide file tree
Showing 23 changed files with 307 additions and 139 deletions.
2 changes: 1 addition & 1 deletion babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ module.exports = function (api) {
exclude: [
"transform-typeof-symbol",
// We need to enable useBuiltIns
"proposal-object-rest-spread",
"transform-object-rest-spread",
],
};

Expand Down
27 changes: 21 additions & 6 deletions packages/babel-core/src/config/files/module-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,33 @@ export const supportsESM = semver.satisfies(
export default function* loadCodeDefault(
filepath: string,
asyncError: string,
// TODO(Babel 8): Remove this
fallbackToTranspiledModule: boolean = false,
): Handler<unknown> {
switch (path.extname(filepath)) {
case ".cjs":
return loadCjsDefault(filepath, fallbackToTranspiledModule);
if (process.env.BABEL_8_BREAKING) {
return loadCjsDefault(filepath);
} else {
return loadCjsDefault(
filepath,
// @ts-ignore(Babel 7 vs Babel 8) Removed in Babel 8
/* fallbackToTranspiledModule */ arguments[2],
);
}
case ".mjs":
break;
case ".cts":
return loadCtsDefault(filepath);
default:
try {
return loadCjsDefault(filepath, fallbackToTranspiledModule);
if (process.env.BABEL_8_BREAKING) {
return loadCjsDefault(filepath);
} else {
return loadCjsDefault(
filepath,
// @ts-ignore(Babel 7 vs Babel 8) Removed in Babel 8
/* fallbackToTranspiledModule */ arguments[2],
);
}
} catch (e) {
if (e.code !== "ERR_REQUIRE_ESM") throw e;
}
Expand Down Expand Up @@ -122,13 +136,14 @@ function loadCtsDefault(filepath: string) {
}
}

function loadCjsDefault(filepath: string, fallbackToTranspiledModule: boolean) {
function loadCjsDefault(filepath: string) {
const module = endHiddenCallStack(require)(filepath);
if (process.env.BABEL_8_BREAKING) {
return module?.__esModule ? module.default : module;
} else {
return module?.__esModule
? module.default || (fallbackToTranspiledModule ? module : undefined)
? module.default ||
/* fallbackToTranspiledModule */ (arguments[1] ? module : undefined)
: module;
}
}
Expand Down
30 changes: 20 additions & 10 deletions packages/babel-core/src/config/files/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,16 +211,26 @@ function* requireModule(type: string, name: string): Handler<unknown> {
if (!process.env.BABEL_8_BREAKING) {
LOADING_MODULES.add(name);
}
return yield* loadCodeDefault(
name,
`You appear to be using a native ECMAScript module ${type}, ` +
"which is only supported when running Babel asynchronously.",
// For backward compatibility, we need to support malformed presets
// defined as separate named exports rather than a single default
// export.
// See packages/babel-core/test/fixtures/option-manager/presets/es2015_named.js
true,
);

if (process.env.BABEL_8_BREAKING) {
return yield* loadCodeDefault(
name,
`You appear to be using a native ECMAScript module ${type}, ` +
"which is only supported when running Babel asynchronously.",
);
} else {
return yield* loadCodeDefault(
name,
`You appear to be using a native ECMAScript module ${type}, ` +
"which is only supported when running Babel asynchronously.",
// For backward compatibility, we need to support malformed presets
// defined as separate named exports rather than a single default
// export.
// See packages/babel-core/test/fixtures/option-manager/presets/es2015_named.js
// @ts-ignore(Babel 7 vs Babel 8) This param has been removed
true,
);
}
} catch (err) {
err.message = `[BABEL]: ${err.message} (While processing: ${name})`;
throw err;
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-core/src/config/item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class ConfigItem {
*/
_descriptor: UnloadedDescriptor;

// TODO(Babel 8): Check if this symbol needs to be updated
// TODO(Babel 9): Check if this symbol needs to be updated
/**
* Used to detect ConfigItem instances from other Babel instances.
*/
Expand Down
16 changes: 8 additions & 8 deletions packages/babel-core/src/transformation/plugin-pass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,6 @@ export default class PluginPass {
return this.file.addHelper(name);
}

// TODO: Remove this in Babel 8
addImport() {
this.file.addImport();
}

buildCodeFrameError(
node: NodeLocation | undefined | null,
msg: string,
Expand All @@ -53,9 +48,14 @@ export default class PluginPass {
}

if (!process.env.BABEL_8_BREAKING) {
(PluginPass as any).prototype.getModuleName = function getModuleName():
| string
| undefined {
(PluginPass as any).prototype.getModuleName = function getModuleName(
this: PluginPass,
): string | undefined {
return this.file.getModuleName();
};
(PluginPass as any).prototype.addImport = function addImport(
this: PluginPass,
): void {
this.file.addImport();
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,12 @@ export function createClassFeaturePlugin({
feature,
loose,
manipulateOptions,
// @ts-ignore(Babel 7 vs Babel 8) TODO(Babel 8): Remove the default value
api = { assumption: () => void 0 },
api,
inherits,
}: Options): PluginObject {
if (!process.env.BABEL_8_BREAKING) {
api ??= { assumption: () => void 0 as any } as any;
}
const setPublicClassFields = api.assumption("setPublicClassFields");
const privateFieldsAsSymbols = api.assumption("privateFieldsAsSymbols");
const privateFieldsAsProperties = api.assumption("privateFieldsAsProperties");
Expand Down
24 changes: 16 additions & 8 deletions packages/babel-plugin-transform-arrow-functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,23 @@ export default declare((api, options: Options) => {
// was queued up.
if (!path.isArrowFunctionExpression()) return;

path.arrowFunctionToExpression({
// While other utils may be fine inserting other arrows to make more transforms possible,
// the arrow transform itself absolutely cannot insert new arrow functions.
allowInsertArrow: false,
noNewArrows,
if (process.env.BABEL_8_BREAKING) {
path.arrowFunctionToExpression({
// While other utils may be fine inserting other arrows to make more transforms possible,
// the arrow transform itself absolutely cannot insert new arrow functions.
allowInsertArrow: false,
noNewArrows,
});
} else {
path.arrowFunctionToExpression({
allowInsertArrow: false,
noNewArrows,

// TODO(Babel 8): This is only needed for backward compat with @babel/traverse <7.13.0
specCompliant: !noNewArrows,
});
// This is only needed for backward compat with @babel/traverse <7.13.0
// @ts-ignore(Babel 7 vs Babel 8) Removed in Babel 8
specCompliant: !noNewArrows,
});
}
},
},
};
Expand Down
63 changes: 37 additions & 26 deletions packages/babel-plugin-transform-computed-properties/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,18 @@ type PropertyInfo = {
state: PluginPass;
};

// TODO(Babel 8): Remove this
const DefineAccessorHelper = template.expression.ast`
function (type, obj, key, fn) {
var desc = { configurable: true, enumerable: true };
desc[type] = fn;
return Object.defineProperty(obj, key, desc);
}`;
// @ts-expect-error undocumented _compact node property
DefineAccessorHelper._compact = true;
if (!process.env.BABEL_8_BREAKING) {
// eslint-disable-next-line no-var
var DefineAccessorHelper = template.expression.ast`
function (type, obj, key, fn) {
var desc = { configurable: true, enumerable: true };
desc[type] = fn;
return Object.defineProperty(obj, key, desc);
}
`;
// @ts-expect-error undocumented _compact node property
DefineAccessorHelper._compact = true;
}

export default declare((api, options: Options) => {
api.assertVersion(7);
Expand All @@ -44,26 +47,34 @@ export default declare((api, options: Options) => {
key: t.Expression,
fn: t.Expression,
) {
let helper: t.Identifier;
if (state.availableHelper("defineAccessor")) {
helper = state.addHelper("defineAccessor");
if (process.env.BABEL_8_BREAKING) {
return t.callExpression(state.addHelper("defineAccessor"), [
t.stringLiteral(type),
obj,
key,
fn,
]);
} else {
// Fallback for @babel/helpers <= 7.20.6, manually add helper function
// TODO(Babel 8): Remove this
const file = state.file;
helper = file.get("fallbackDefineAccessorHelper");
if (!helper) {
const id = file.scope.generateUidIdentifier("defineAccessor");
file.scope.push({
id,
init: DefineAccessorHelper,
});
file.set("fallbackDefineAccessorHelper", (helper = id));
let helper: t.Identifier;
if (state.availableHelper("defineAccessor")) {
helper = state.addHelper("defineAccessor");
} else {
// Fallback for @babel/helpers <= 7.20.6, manually add helper function
const file = state.file;
helper = file.get("fallbackDefineAccessorHelper");
if (!helper) {
const id = file.scope.generateUidIdentifier("defineAccessor");
file.scope.push({
id,
init: DefineAccessorHelper,
});
file.set("fallbackDefineAccessorHelper", (helper = id));
}
helper = t.cloneNode(helper);
}
helper = t.cloneNode(helper);
}

return t.callExpression(helper, [t.stringLiteral(type), obj, key, fn]);
return t.callExpression(helper, [t.stringLiteral(type), obj, key, fn]);
}
}

/**
Expand Down
22 changes: 13 additions & 9 deletions packages/babel-plugin-transform-for-of/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,13 @@ export default declare((api, options: Options) => {
);
}

// TODO: Remove in Babel 8
if (allowArrayLike && /^7\.\d\./.test(api.version)) {
throw new Error(
`The allowArrayLike is only supported when using @babel/core@^7.10.0`,
);
if (!process.env.BABEL_8_BREAKING) {
// TODO: Remove in Babel 8
if (allowArrayLike && /^7\.\d\./.test(api.version)) {
throw new Error(
`The allowArrayLike is only supported when using @babel/core@^7.10.0`,
);
}
}
}

Expand Down Expand Up @@ -217,10 +219,12 @@ export default declare((api, options: Options) => {
return;
}

if (!state.availableHelper(builder.helper)) {
// Babel <7.9.0 doesn't support this helper
transformWithoutHelper(skipIteratorClosing, path, state);
return;
if (!process.env.BABEL_8_BREAKING) {
if (!state.availableHelper(builder.helper)) {
// Babel <7.9.0 doesn't support this helper
transformWithoutHelper(skipIteratorClosing, path, state);
return;
}
}

const { node, parent, scope } = path;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { NodePath } from "@babel/traverse";

// This is the legacy implementation, which inlines all the code.
// It must be kept for compatibility reasons.
// TODO(Babel 8): Remove this code.
// TODO(Babel 8): Remove this file.

export default function transformWithoutHelper(
loose: boolean | void,
Expand Down
28 changes: 16 additions & 12 deletions packages/babel-plugin-transform-regenerator/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ export default declare(({ types: t, assertVersion }) => {
// We visit MemberExpression so that we always transform
// regeneratorRuntime before babel-plugin-polyfill-regenerator.
MemberExpression(path) {
if (!this.availableHelper?.("regeneratorRuntime")) {
// When using an older @babel/helpers version, fallback
// to the old behavior.
// TODO: Remove this in Babel 8.
return;
if (!process.env.BABEL_8_BREAKING) {
if (!this.availableHelper?.("regeneratorRuntime")) {
// When using an older @babel/helpers version, fallback
// to the old behavior.
// TODO: Remove this in Babel 8.
return;
}
}

const obj = path.get("object");
Expand All @@ -27,13 +29,15 @@ export default declare(({ types: t, assertVersion }) => {
| t.Identifier
| t.ArrowFunctionExpression;

if (
// TODO: Remove this in Babel 8, it's necessary to
// avoid the IIFE when using older Babel versions.
t.isArrowFunctionExpression(helper)
) {
obj.replaceWith(helper.body);
return;
if (!process.env.BABEL_8_BREAKING) {
if (
// TODO: Remove this in Babel 8, it's necessary to
// avoid the IIFE when using older Babel versions.
t.isArrowFunctionExpression(helper)
) {
obj.replaceWith(helper.body);
return;
}
}

obj.replaceWith(t.callExpression(helper, []));
Expand Down
14 changes: 9 additions & 5 deletions packages/babel-plugin-transform-unicode-escapes/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@ export default declare(api => {
const unicodeEscape = /(\\+)u\{([0-9a-fA-F]+)\}/g;

function escape(code: number) {
let str = code.toString(16);
// Sigh, node 6 doesn't have padStart
// TODO: Remove in Babel 8, when we drop node 6.
while (str.length < 4) str = "0" + str;
return "\\u" + str;
if (process.env.BABEL_8_BREAKING) {
return "\\u" + code.toString(16).padStart(4, "0");
} else {
let str = code.toString(16);
// Sigh, node 6 doesn't have padStart
// TODO: Remove in Babel 8, when we drop node 6.
while (str.length < 4) str = "0" + str;
return "\\u" + str;
}
}

function replacer(match: string, backslashes: string[], code: string) {
Expand Down
16 changes: 8 additions & 8 deletions packages/babel-preset-env/src/normalize-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,14 @@ const expandIncludesAndExcludes = (
} else {
re = filter;
}
const items = filterableItems.filter(
item =>
re.test(item) ||
// For backwards compatibility, we also support matching against the
// proposal- name.
// TODO(Babel 8): Remove this.
re.test(item.replace(/^transform-/, "proposal-")),
);
const items = filterableItems.filter(item => {
return process.env.BABEL_8_BREAKING
? re.test(item)
: re.test(item) ||
// For backwards compatibility, we also support matching against the
// proposal- name.
re.test(item.replace(/^transform-/, "proposal-"));
});
if (items.length === 0) invalidFilters.push(filter);
return items;
});
Expand Down

0 comments on commit c060e5e

Please sign in to comment.