Skip to content

Commit

Permalink
chore: Improve development experience about global variables (#15646)
Browse files Browse the repository at this point in the history
Co-authored-by: Nicolò Ribaudo <nicolo.ribaudo@gmail.com>
  • Loading branch information
liuxingbaoyu and nicolo-ribaudo committed May 26, 2023
1 parent fef5b40 commit f64974d
Show file tree
Hide file tree
Showing 32 changed files with 915 additions and 703 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ module.exports = {
},
},
{
files: ["scripts/**/*.js"],
files: ["scripts/**/*.{js,cjs}"],
rules: {
"import/no-extraneous-dependencies": ["error", { packageDir: "." }],
},
Expand Down
12 changes: 2 additions & 10 deletions Gulpfile.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,9 @@ import rollupBabelSource from "./scripts/rollup-plugin-babel-source.js";
import rollupStandaloneInternals from "./scripts/rollup-plugin-standalone-internals.js";
import formatCode from "./scripts/utils/formatCode.js";
import { log } from "./scripts/utils/logger.cjs";
import { USE_ESM, commonJS } from "$repo-utils";

let USE_ESM = false;
try {
const type = fs
.readFileSync(new URL(".module-type", import.meta.url), "utf-8")
.trim();
USE_ESM = type === "module";
} catch {}

const require = createRequire(import.meta.url);
const monorepoRoot = path.dirname(fileURLToPath(import.meta.url));
const { require, __dirname: monorepoRoot } = commonJS(import.meta.url);

const defaultPackagesGlob = "./@(codemods|packages|eslint)/*";
const defaultSourcesGlob = `${defaultPackagesGlob}/src/**/{*.js,*.cjs,!(*.d).ts}`;
Expand Down
47 changes: 39 additions & 8 deletions babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,10 @@ function transformNamedBabelTypesImportToDestructuring({
};
}

/**
* @param {import("@babel/core")} pluginAPI
* @returns {import("@babel/core").PluginObj}
*/
function pluginImportMetaUrl({ types: t, template }) {
const isImportMeta = node =>
t.isMetaProperty(node) &&
Expand All @@ -675,23 +679,50 @@ function pluginImportMetaUrl({ types: t, template }) {
const { node } = path;

if (
!t.isIdentifier(node.callee, { name: "fileURLToPath" }) ||
node.arguments.length !== 1
(function () {
if (
!t.isIdentifier(node.callee, {
name: "fileURLToPath",
}) ||
node.arguments.length !== 1
) {
return;
}

const arg = node.arguments[0];

if (
!t.isMemberExpression(arg, {
computed: false,
}) ||
!t.isIdentifier(arg.property, {
name: "url",
}) ||
!isImportMeta(arg.object)
) {
return;
}
path.replaceWith(t.identifier("__filename"));
return true;
})()
) {
return;
}

const arg = node.arguments[0];

if (
!t.isMemberExpression(arg, { computed: false }) ||
!t.isIdentifier(arg.property, { name: "url" }) ||
!isImportMeta(arg.object)
!t.isIdentifier(node.callee, { name: "commonJS" }) ||
node.arguments.length !== 1
) {
return;
}

path.replaceWith(t.identifier("__filename"));
const binding = path.scope.getBinding("commonJS");
if (!binding) return;

if (binding.path.isImportSpecifier()) {
path.parentPath.parentPath.assertVariableDeclaration();
path.parentPath.parentPath.remove();
}
},

// const require = createRequire(import.meta.url)
Expand Down
10 changes: 1 addition & 9 deletions eslint/babel-eslint-tests/test/integration/config-files.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
import { ESLint } from "eslint";
import path from "path";
import { fileURLToPath } from "url";
import fs from "fs";

let USE_ESM = false;
try {
const type = fs
.readFileSync(new URL("../../../../.module-type", import.meta.url), "utf-8")
.trim();
USE_ESM = type === "module";
} catch {}
import { USE_ESM } from "$repo-utils";

describe("Babel config files", () => {
const itESM = USE_ESM ? it : it.skip;
Expand Down
9 changes: 9 additions & 0 deletions lib/globals.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
declare const USE_ESM: boolean;
declare const IS_STANDALONE: boolean;
declare const PACKAGE_JSON: { name: string; version: string };

declare namespace NodeJS {
export interface ProcessEnv {
BABEL_8_BREAKING: string;
}
}
8 changes: 0 additions & 8 deletions lib/package-json.d.ts

This file was deleted.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
},
"packageManager": "yarn@3.5.0",
"devDependencies": {
"$repo-utils": "link:./scripts/repo-utils",
"@babel/cli": "^7.21.0",
"@babel/core": "^7.21.0",
"@babel/eslint-config-internal": "workspace:^",
Expand Down
2 changes: 0 additions & 2 deletions packages/babel-core/src/config/files/import-meta-resolve.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { resolve as polyfill } from "../../vendor/import-meta-resolve";

declare const USE_ESM: boolean;

let importMetaResolve: (specifier: string, parent: string) => string;

if (USE_ESM) {
Expand Down
3 changes: 0 additions & 3 deletions packages/babel-core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
declare const PACKAGE_JSON: { name: string; version: string };
declare const USE_ESM: boolean, IS_STANDALONE: boolean;

export const version = PACKAGE_JSON.version;

export { default as File } from "./transformation/file/file";
Expand Down
16 changes: 2 additions & 14 deletions packages/babel-core/test/config-ts.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,9 @@
import { loadPartialConfigSync } from "../lib/index.js";
import path from "path";
import { readFileSync } from "fs";
import { fileURLToPath } from "url";
import { createRequire } from "module";
import semver from "semver";
import { USE_ESM, commonJS } from "$repo-utils";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);

let USE_ESM = false;
try {
const type = readFileSync(
new URL("../../../.module-type", import.meta.url),
"utf-8",
).trim();
USE_ESM = type === "module";
} catch {}
const { __dirname, require } = commonJS(import.meta.url);

// We skip older versions of node testing for two reasons.
// 1. ts-node does not support the old version of node.
Expand Down
22 changes: 4 additions & 18 deletions packages/babel-core/test/helpers/esm.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,16 @@
import cp from "child_process";
import util from "util";
import path from "path";
import fs from "fs";
import { fileURLToPath } from "url";
import { createRequire } from "module";
import { USE_ESM, commonJS } from "$repo-utils";

import * as babel from "../../lib/index.js";

const require = createRequire(import.meta.url);
const dirname = path.dirname(fileURLToPath(import.meta.url));
const { require, __dirname } = commonJS(import.meta.url);

// "minNodeVersion": "10.0.0" <-- For Ctrl+F when dropping node 10
export const supportsESM = parseInt(process.versions.node) >= 12;

export const outputType = (() => {
try {
return fs
.readFileSync(
new URL("../../../../.module-type", import.meta.url),
"utf-8",
)
.trim();
} catch (_) {
return "script";
}
})();
export const outputType = USE_ESM ? "module" : "script";

export const isMJS = file => path.extname(file) === ".mjs";

Expand All @@ -40,7 +26,7 @@ export function skipUnsupportedESM(name) {
return false;
}

export function loadOptionsAsync({ filename, cwd = dirname }, mjs) {
export function loadOptionsAsync({ filename, cwd = __dirname }, mjs) {
if (mjs) {
// import() crashes with jest
return spawn("load-options-async", filename, cwd);
Expand Down
11 changes: 1 addition & 10 deletions packages/babel-core/test/option-manager.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as babel from "../lib/index.js";
import path from "path";
import { fileURLToPath } from "url";
import { readFileSync } from "fs";
import { USE_ESM } from "$repo-utils";

const cwd = path.dirname(fileURLToPath(import.meta.url));

Expand All @@ -13,15 +13,6 @@ function loadOptionsAsync(opts) {
return babel.loadOptionsAsync({ cwd, ...opts });
}

let USE_ESM = false;
try {
const type = readFileSync(
new URL("../../../.module-type", import.meta.url),
"utf-8",
).trim();
USE_ESM = type === "module";
} catch {}

const itBabel7 = process.env.BABEL_8_BREAKING ? it.skip : it;
const itBabel7cjs = process.env.BABEL_8_BREAKING || USE_ESM ? it.skip : it;

Expand Down
1 change: 0 additions & 1 deletion packages/babel-helper-compilation-targets/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ export { TargetNames };

const ESM_SUPPORT = browserModulesData["es6.module"];

declare const PACKAGE_JSON: { name: string; version: string };
const v = new OptionValidator(PACKAGE_JSON.name);

function validateTargetNames(targets: Targets): TargetsTuple {
Expand Down
2 changes: 0 additions & 2 deletions packages/babel-helper-compilation-targets/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { OptionValidator } from "@babel/helper-validator-option";
import { unreleasedLabels } from "./targets";
import type { Target, Targets } from "./types";

declare const PACKAGE_JSON: { name: string; version: string };

const versionRegExp = /^(\d+|\d+.\d+)$/;

const v = new OptionValidator(PACKAGE_JSON.name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import { assertFieldTransformed } from "./typescript";

export { FEATURES, enableFeature, injectInitialization, buildCheckInRHS };

declare const PACKAGE_JSON: { name: string; version: string };
const versionKey = "@babel/plugin-class-features/version";

interface Options {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
} from "./features";
import { generateRegexpuOptions, canSkipRegexpu, transformFlags } from "./util";

declare const PACKAGE_JSON: { name: string; version: string };
const versionKey = "@babel/plugin-regexp-features/version";

export interface Options {
Expand Down
1 change: 0 additions & 1 deletion packages/babel-helper-environment-visitor/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { NodePath, Visitor } from "@babel/traverse";
import type * as t from "@babel/types";

declare const USE_ESM: boolean, IS_STANDALONE: boolean;
if (!process.env.BABEL_8_BREAKING) {
if (!USE_ESM) {
if (!IS_STANDALONE) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import * as t from "@babel/types";
import template from "@babel/template";

declare const USE_ESM: boolean, IS_STANDALONE: boolean;
if (!process.env.BABEL_8_BREAKING) {
if (!USE_ESM) {
if (!IS_STANDALONE) {
Expand Down
1 change: 0 additions & 1 deletion packages/babel-helper-module-transforms/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ import type { NodePath } from "@babel/traverse";

export { buildDynamicImport } from "./dynamic-import";

declare const USE_ESM: boolean, IS_STANDALONE: boolean;
if (!process.env.BABEL_8_BREAKING) {
if (!USE_ESM) {
if (!IS_STANDALONE) {
Expand Down
1 change: 0 additions & 1 deletion packages/babel-helper-replace-supers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import {
} from "@babel/types";
import type * as t from "@babel/types";

declare const USE_ESM: boolean, IS_STANDALONE: boolean;
if (!process.env.BABEL_8_BREAKING) {
if (!USE_ESM) {
if (!IS_STANDALONE) {
Expand Down
1 change: 0 additions & 1 deletion packages/babel-node/src/_babel-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ program.option(
program.option("-w, --plugins [string]", "", collect);
program.option("-b, --presets [string]", "", collect);

declare const PACKAGE_JSON: { name: string; version: string };
program.version(PACKAGE_JSON.version);
program.usage("[options] [ -e script | script.js ] [arguments]");
program.parse(process.argv);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import { addNamed, isModule } from "@babel/helper-module-imports";
import { OptionValidator } from "@babel/helper-validator-option";
import type { NodePath } from "@babel/traverse";

declare const PACKAGE_JSON: { name: string; version: string };
const v = new OptionValidator(PACKAGE_JSON.name);

export interface Options extends SyntaxOptions {
Expand Down
2 changes: 0 additions & 2 deletions packages/babel-plugin-transform-dynamic-import/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ the @babel/plugin-syntax-dynamic-import plugin and let your
bundler handle dynamic imports.
`;

declare const PACKAGE_JSON: { name: string; version: string };

export default declare(api => {
api.assertVersion(7);

Expand Down
2 changes: 0 additions & 2 deletions packages/babel-preset-env/src/normalize-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ import type {
PluginListOption,
} from "./types";

declare const PACKAGE_JSON: { name: string; version: string };

const v = new OptionValidator(PACKAGE_JSON.name);

const allPluginsList = Object.keys(pluginsList);
Expand Down
19 changes: 5 additions & 14 deletions packages/babel-register/test/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { createRequire, Module } from "module";
import { Module } from "module";
import path from "path";
import fs from "fs";
import child from "child_process";
import { fileURLToPath } from "url";
import { USE_ESM, commonJS } from "$repo-utils";

const dirname = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
const { __dirname, require } = commonJS(import.meta.url);

const testCacheFilename = path.join(dirname, ".index.babel");
const testCacheFilename = path.join(__dirname, ".index.babel");
const testFile = require.resolve("./fixtures/babelrc/es2015");
const testFileLog = require.resolve("./fixtures/babelrc/log");
const testFileMjs = require.resolve("./fixtures/mjs-babelrc/es2015");
Expand Down Expand Up @@ -36,14 +35,6 @@ function resetCache() {

const OLD_JEST_MOCKS = !!jest.doMock;

let USE_ESM = false;
try {
const type = fs
.readFileSync(new URL("../../../.module-type", import.meta.url), "utf-8")
.trim();
USE_ESM = type === "module";
} catch {}

describe("@babel/register", function () {
let currentHook, currentOptions, sourceMapSupport;

Expand Down Expand Up @@ -408,7 +399,7 @@ describe("@babel/register", function () {
}
});

function spawnNodeAsync(args, cwd = dirname, env) {
function spawnNodeAsync(args, cwd = __dirname, env) {
const spawn = child.spawn(process.execPath, args, { cwd, env });

let output = "";
Expand Down
2 changes: 0 additions & 2 deletions packages/babel-traverse/src/path/conversion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,6 @@ export function ensureBlock(
return this.node;
}

declare const USE_ESM: boolean;

if (!process.env.BABEL_8_BREAKING) {
if (!USE_ESM) {
/**
Expand Down

0 comments on commit f64974d

Please sign in to comment.