From b63be942cef487fa31a7fa35bd7694076d5b7ad9 Mon Sep 17 00:00:00 2001 From: Karan Sapolia Date: Sat, 30 Jan 2021 23:06:21 +0530 Subject: [PATCH] Use native ESM for dev scripts (#12296) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Nicolò Ribaudo --- .codesandbox/ci.json | 3 +- .eslintrc.js => .eslintrc.cjs | 15 ++++ .github/workflows/ci.yml | 5 +- Gulpfile.js => Gulpfile.mjs | 77 ++++++++++--------- Makefile | 4 +- package.json | 3 +- .../scripts/generators/asserts.js | 9 +-- .../scripts/generators/validators.js | 15 ++-- .../scripts/generators/virtual-types.js | 8 +- packages/babel-traverse/scripts/package.json | 1 + .../babel-types/scripts/generators/asserts.js | 7 +- .../scripts/generators/ast-types.js | 10 +-- .../scripts/generators/builders.js | 16 ++-- .../scripts/generators/constants.js | 7 +- .../babel-types/scripts/generators/docs.js | 36 ++++----- .../babel-types/scripts/generators/flow.js | 8 +- .../scripts/generators/typescript-legacy.js | 8 +- .../scripts/generators/validators.js | 7 +- packages/babel-types/scripts/package.json | 1 + .../scripts/utils/formatBuilderName.js | 6 +- .../babel-types/scripts/utils/lowerFirst.js | 5 +- .../scripts/utils/stringifyValidator.js | 4 +- .../scripts/utils/toFunctionName.js | 4 +- scripts/generators/readmes.js | 7 +- scripts/generators/tsconfig.js | 13 +++- .../utils/bump-babel-dependencies.js | 5 +- scripts/package.json | 1 + scripts/parser-tests/flow/index.js | 15 ++-- scripts/parser-tests/test262/index.js | 13 ++-- .../parser-tests/typescript/error-codes.js | 2 +- scripts/parser-tests/typescript/index.js | 17 ++-- .../parser-tests/utils/parser-test-runner.js | 10 +-- scripts/rollup-plugin-babel-source.js | 23 ++++-- scripts/utils/formatCode.js | 25 ++---- ...e-corejs3.mjs => babel-runtime-corejs3.js} | 0 .../{babel-runtime.mjs => babel-runtime.js} | 0 test/esm/{index.mjs => index.js} | 6 +- test/esm/package.json | 2 +- test/esm/{test-runner.mjs => test-runner.js} | 0 39 files changed, 205 insertions(+), 193 deletions(-) rename .eslintrc.js => .eslintrc.cjs (85%) rename Gulpfile.js => Gulpfile.mjs (87%) create mode 100644 packages/babel-traverse/scripts/package.json create mode 100644 packages/babel-types/scripts/package.json create mode 100644 scripts/package.json rename test/esm/{babel-runtime-corejs3.mjs => babel-runtime-corejs3.js} (100%) rename test/esm/{babel-runtime.mjs => babel-runtime.js} (100%) rename test/esm/{index.mjs => index.js} (62%) rename test/esm/{test-runner.mjs => test-runner.js} (100%) diff --git a/.codesandbox/ci.json b/.codesandbox/ci.json index f260124b7c..6b8111ffec 100644 --- a/.codesandbox/ci.json +++ b/.codesandbox/ci.json @@ -1,5 +1,6 @@ { "buildCommand": "codesandbox:build", "sandboxes": ["7s08o", "vhm64"], - "packages": ["packages/*"] + "packages": ["packages/*"], + "node": "14" } diff --git a/.eslintrc.js b/.eslintrc.cjs similarity index 85% rename from .eslintrc.js rename to .eslintrc.cjs index a900e19c0c..143e52e2d3 100644 --- a/.eslintrc.js +++ b/.eslintrc.cjs @@ -87,5 +87,20 @@ module.exports = { ], }, }, + { + files: ["packages/babel-traverse/scripts/**/*.js"], + rules: { + "import/no-extraneous-dependencies": [ + "error", + { packageDir: "./packages/babel-traverse" }, + ], + }, + }, + { + files: ["scripts/**/*.js"], + rules: { + "import/no-extraneous-dependencies": ["error", { packageDir: "." }], + }, + }, ], }; diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7cc07c7baa..1ce79aa9da 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,8 +65,9 @@ jobs: name: Build Babel Artifacts needs: prepare-yarn-cache runs-on: ubuntu-latest - env: - YARN_NODE_LINKER: pnp # use pnp linker for better linking performance and stricter checks + # Yarn PnP does not support native ESM yet (https://github.com/yarnpkg/berry/issues/638) + # env: + # YARN_NODE_LINKER: pnp # use pnp linker for better linking performance and stricter checks steps: - name: Checkout code uses: actions/checkout@v2 diff --git a/Gulpfile.js b/Gulpfile.mjs similarity index 87% rename from Gulpfile.js rename to Gulpfile.mjs index b9beb8b8ec..51feb35d5d 100644 --- a/Gulpfile.js +++ b/Gulpfile.mjs @@ -1,26 +1,33 @@ -"use strict"; +import path from "path"; +import fs from "fs"; +import { createRequire } from "module"; +import { fileURLToPath } from "url"; -const plumber = require("gulp-plumber"); -const through = require("through2"); -const chalk = require("chalk"); -const newer = require("gulp-newer"); -const babel = require("gulp-babel"); -const camelCase = require("lodash/camelCase"); -const fancyLog = require("fancy-log"); -const filter = require("gulp-filter"); -const gulp = require("gulp"); -const path = require("path"); -const fs = require("fs"); -const rollup = require("rollup"); -const rollupBabel = require("@rollup/plugin-babel").default; -const rollupBabelSource = require("./scripts/rollup-plugin-babel-source"); -const rollupCommonJs = require("@rollup/plugin-commonjs"); -const rollupJson = require("@rollup/plugin-json"); -const rollupNodePolyfills = require("rollup-plugin-node-polyfills"); -const rollupNodeResolve = require("@rollup/plugin-node-resolve").default; -const rollupReplace = require("@rollup/plugin-replace"); -const { terser: rollupTerser } = require("rollup-plugin-terser"); -const { default: rollupDts } = require("rollup-plugin-dts"); +import plumber from "gulp-plumber"; +import through from "through2"; +import chalk from "chalk"; +import newer from "gulp-newer"; +import babel from "gulp-babel"; +import camelCase from "lodash/camelCase.js"; +import fancyLog from "fancy-log"; +import filter from "gulp-filter"; +import gulp from "gulp"; +import { rollup } from "rollup"; +import { babel as rollupBabel } from "@rollup/plugin-babel"; +import rollupCommonJs from "@rollup/plugin-commonjs"; +import rollupJson from "@rollup/plugin-json"; +import rollupNodePolyfills from "rollup-plugin-node-polyfills"; +import rollupNodeResolve from "@rollup/plugin-node-resolve"; +import rollupReplace from "@rollup/plugin-replace"; +import { terser as rollupTerser } from "rollup-plugin-terser"; +import _rollupDts from "rollup-plugin-dts"; +const { default: rollupDts } = _rollupDts; + +import rollupBabelSource from "./scripts/rollup-plugin-babel-source.js"; +import formatCode from "./scripts/utils/formatCode.js"; + +const require = createRequire(import.meta.url); +const monorepoRoot = path.dirname(fileURLToPath(import.meta.url)); const defaultPackagesGlob = "./@(codemods|packages|eslint)/*"; const defaultSourcesGlob = `${defaultPackagesGlob}/src/**/{*.js,!(*.d).ts}`; @@ -92,15 +99,16 @@ function rename(fn) { * @param {string} message */ function generateHelpers(generator, dest, filename, message) { - const formatCode = require("./scripts/utils/formatCode"); const stream = gulp - .src(".", { base: __dirname }) + .src(".", { base: monorepoRoot }) .pipe(errorsLogger()) .pipe( - through.obj(function (file, enc, callback) { + through.obj(async (file, enc, callback) => { + const { default: generateCode } = await import(generator); + file.path = filename; file.contents = Buffer.from( - formatCode(require(generator)(filename), dest + file.path) + formatCode(generateCode(filename), dest + file.path) ); fancyLog(`${chalk.green("✔")} Generated ${message}`); callback(null, file); @@ -119,7 +127,7 @@ function generateHelpers(generator, dest, filename, message) { */ async function generateTypeHelpers(helperKind, filename = "index.ts") { return generateHelpers( - `./packages/babel-types/scripts/generators/${helperKind}`, + `./packages/babel-types/scripts/generators/${helperKind}.js`, `./packages/babel-types/src/${helperKind}/generated/`, filename, `@babel/types -> ${helperKind}` @@ -133,7 +141,7 @@ async function generateTypeHelpers(helperKind, filename = "index.ts") { */ async function generateTraverseHelpers(helperKind) { return generateHelpers( - `./packages/babel-traverse/scripts/generators/${helperKind}`, + `./packages/babel-traverse/scripts/generators/${helperKind}.js`, `./packages/babel-traverse/src/path/generated/`, `${helperKind}.ts`, `@babel/traverse -> ${helperKind}` @@ -142,9 +150,8 @@ async function generateTraverseHelpers(helperKind) { function generateStandalone() { const dest = "./packages/babel-standalone/src/generated/"; - const formatCode = require("./scripts/utils/formatCode"); return gulp - .src(babelStandalonePluginConfigGlob, { base: __dirname }) + .src(babelStandalonePluginConfigGlob, { base: monorepoRoot }) .pipe( through.obj((file, enc, callback) => { fancyLog("Generating @babel/standalone files"); @@ -190,7 +197,7 @@ function finish(stream) { } function getFiles(glob, { include, exclude }) { - let stream = gulp.src(glob, { base: __dirname }); + let stream = gulp.src(glob, { base: monorepoRoot }); if (exclude) { const filters = exclude.map(p => `!**/${p}/**`); @@ -206,7 +213,7 @@ function getFiles(glob, { include, exclude }) { } function buildBabel(exclude) { - const base = __dirname; + const base = monorepoRoot; return getFiles(defaultSourcesGlob, { exclude: exclude && exclude.map(p => p.src), @@ -259,7 +266,7 @@ function buildRollup(packages, targetBrowsers) { } const input = getIndexFromPackage(src); fancyLog(`Compiling '${chalk.cyan(input)}' with rollup ...`); - const bundle = await rollup.rollup({ + const bundle = await rollup({ input, external, onwarn(warning, warn) { @@ -352,7 +359,7 @@ function buildRollupDts(packages) { packages.map(async packageName => { const input = `${packageName}/lib/index.d.ts`; fancyLog(`Bundling '${chalk.cyan(input)}' with rollup ...`); - const bundle = await rollup.rollup({ + const bundle = await rollup({ input, plugins: [rollupDts()], }); @@ -378,7 +385,7 @@ function removeDts(exclude) { function copyDts(packages) { return getFiles(`${defaultPackagesGlob}/src/**/*.d.ts`, { include: packages }) .pipe(rename(file => path.resolve(file.base, mapSrcToLib(file.relative)))) - .pipe(gulp.dest(__dirname)); + .pipe(gulp.dest(monorepoRoot)); } const libBundles = [ diff --git a/Makefile b/Makefile index 0061835a65..01097c6580 100644 --- a/Makefile +++ b/Makefile @@ -87,12 +87,12 @@ check-compat-data-ci: $(MAKE) check-compat-data lint: - BABEL_ENV=test $(YARN) eslint scripts $(SOURCES) '*.{js,ts}' --format=codeframe --ext .js,.cjs,.mjs,.ts + BABEL_ENV=test $(YARN) eslint scripts $(SOURCES) '*.{js,cjs,mjs,ts}' --format=codeframe --ext .js,.cjs,.mjs,.ts fix: fix-json fix-js fix-js: - $(YARN) eslint scripts $(SOURCES) '*.{js,ts}' --format=codeframe --ext .js,.cjs,.mjs,.ts --fix + $(YARN) eslint scripts $(SOURCES) '*.{js,cjs,mjs,ts}' --format=codeframe --ext .js,.cjs,.mjs,.ts --fix fix-json: $(YARN) prettier "{$(COMMA_SEPARATED_SOURCES)}/*/test/fixtures/**/options.json" --write --loglevel warn diff --git a/package.json b/package.json index 1f3220a649..42492b3d5a 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,7 @@ "version": "7.12.12", "private": true, "license": "MIT", + "type": "commonjs", "scripts": { "bootstrap": "make bootstrap", "codesandbox:build": "make build-no-bundle", @@ -11,7 +12,7 @@ "lint": "make lint", "test": "make test", "version": "yarn --immutable-cache && git add yarn.lock", - "test:esm": "node test/esm/index.mjs" + "test:esm": "node test/esm/index.js" }, "devDependencies": { "@babel/cli": "^7.12.0", diff --git a/packages/babel-traverse/scripts/generators/asserts.js b/packages/babel-traverse/scripts/generators/asserts.js index 7f666c2307..f10b33eede 100644 --- a/packages/babel-traverse/scripts/generators/asserts.js +++ b/packages/babel-traverse/scripts/generators/asserts.js @@ -1,7 +1,6 @@ -"use strict"; -const t = require("@babel/types"); +import t from "@babel/types"; -module.exports = function generateAsserts() { +export default function generateAsserts() { let output = `/* * This file is auto-generated! Do not modify it directly. * To re-generate run 'make build' @@ -12,7 +11,7 @@ import NodePath from "../index"; export interface NodePathAssetions {`; - for (const type of t.TYPES) { + for (const type of [...t.TYPES].sort()) { output += ` assert${type}( opts?: object, @@ -23,4 +22,4 @@ export interface NodePathAssetions {`; }`; return output; -}; +} diff --git a/packages/babel-traverse/scripts/generators/validators.js b/packages/babel-traverse/scripts/generators/validators.js index b8a956057e..eae98a33e2 100644 --- a/packages/babel-traverse/scripts/generators/validators.js +++ b/packages/babel-traverse/scripts/generators/validators.js @@ -1,11 +1,8 @@ -"use strict"; +import t from "@babel/types"; +import virtualTypes from "../../lib/path/lib/virtual-types.js"; +import definitions from "@babel/types/lib/definitions/index.js"; -const t = require("@babel/types"); -const virtualTypes = require("../../lib/path/lib/virtual-types"); - -const definitions = require("@babel/types/lib/definitions"); - -module.exports = function generateValidators() { +export default function generateValidators() { let output = `/* * This file is auto-generated! Do not modify it directly. * To re-generate run 'make build' @@ -16,7 +13,7 @@ import NodePath from "../index"; export interface NodePathValidators { `; - for (const type of t.TYPES) { + for (const type of [...t.TYPES].sort()) { output += `is${type}(opts?: object): this is NodePath;`; } @@ -34,4 +31,4 @@ export interface NodePathValidators { `; return output; -}; +} diff --git a/packages/babel-traverse/scripts/generators/virtual-types.js b/packages/babel-traverse/scripts/generators/virtual-types.js index 504e32c953..6d55f54caa 100644 --- a/packages/babel-traverse/scripts/generators/virtual-types.js +++ b/packages/babel-traverse/scripts/generators/virtual-types.js @@ -1,8 +1,6 @@ -"use strict"; +import virtualTypes from "../../lib/path/lib/virtual-types.js"; -const virtualTypes = require("../../lib/path/lib/virtual-types"); - -module.exports = function generateValidators() { +export default function generateValidators() { let output = `/* * This file is auto-generated! Do not modify it directly. * To re-generate run 'make build' @@ -23,4 +21,4 @@ export interface VirtualTypeAliases { `; return output; -}; +} diff --git a/packages/babel-traverse/scripts/package.json b/packages/babel-traverse/scripts/package.json new file mode 100644 index 0000000000..5ffd9800b9 --- /dev/null +++ b/packages/babel-traverse/scripts/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/packages/babel-types/scripts/generators/asserts.js b/packages/babel-types/scripts/generators/asserts.js index a517efb31a..bdfd94857f 100644 --- a/packages/babel-types/scripts/generators/asserts.js +++ b/packages/babel-types/scripts/generators/asserts.js @@ -1,5 +1,4 @@ -"use strict"; -const definitions = require("../../lib/definitions"); +import definitions from "../../lib/definitions/index.js"; function addAssertHelper(type) { const result = @@ -14,7 +13,7 @@ function addAssertHelper(type) { `; } -module.exports = function generateAsserts() { +export default function generateAsserts() { let output = `/* * This file is auto-generated! Do not modify it directly. * To re-generate run 'make build' @@ -48,4 +47,4 @@ function assert(type: string, node: any, opts?: any): void { }); return output; -}; +} diff --git a/packages/babel-types/scripts/generators/ast-types.js b/packages/babel-types/scripts/generators/ast-types.js index 98122665de..c37cca5b07 100644 --- a/packages/babel-types/scripts/generators/ast-types.js +++ b/packages/babel-types/scripts/generators/ast-types.js @@ -1,9 +1,7 @@ -"use strict"; +import t from "../../lib/index.js"; +import stringifyValidator from "../utils/stringifyValidator.js"; -const t = require("../../"); -const stringifyValidator = require("../utils/stringifyValidator"); - -module.exports = function generateAstTypes() { +export default function generateAstTypes() { let code = `// NOTE: This file is autogenerated. Do not modify. // See packages/babel-types/scripts/generators/ast-types.js for script used. @@ -118,7 +116,7 @@ export interface ${deprecatedAlias[type]} extends BaseNode { code += "}\n\n"; return code; -}; +} function hasDefault(field) { return field.default != null; diff --git a/packages/babel-types/scripts/generators/builders.js b/packages/babel-types/scripts/generators/builders.js index 6a528fe0c3..3a30e6053c 100644 --- a/packages/babel-types/scripts/generators/builders.js +++ b/packages/babel-types/scripts/generators/builders.js @@ -1,10 +1,8 @@ -"use strict"; -const definitions = require("../../lib/definitions"); -const formatBuilderName = require("../utils/formatBuilderName"); -const lowerFirst = require("../utils/lowerFirst"); - -const t = require("../../"); -const stringifyValidator = require("../utils/stringifyValidator"); +import t from "../../lib/index.js"; +import definitions from "../../lib/definitions/index.js"; +import formatBuilderName from "../utils/formatBuilderName.js"; +import lowerFirst from "../utils/lowerFirst.js"; +import stringifyValidator from "../utils/stringifyValidator.js"; function areAllRemainingFieldsNullable(fieldName, fieldNames, fields) { const index = fieldNames.indexOf(fieldName); @@ -73,11 +71,11 @@ function generateBuilderArgs(type) { return args; } -module.exports = function generateBuilders(kind) { +export default function generateBuilders(kind) { return kind === "uppercase.js" ? generateUppercaseBuilders() : generateLowercaseBuilders(); -}; +} function generateLowercaseBuilders() { let output = `/* diff --git a/packages/babel-types/scripts/generators/constants.js b/packages/babel-types/scripts/generators/constants.js index 8e8b61c50b..68abdbd837 100644 --- a/packages/babel-types/scripts/generators/constants.js +++ b/packages/babel-types/scripts/generators/constants.js @@ -1,7 +1,6 @@ -"use strict"; -const definitions = require("../../lib/definitions"); +import definitions from "../../lib/definitions/index.js"; -module.exports = function generateConstants() { +export default function generateConstants() { let output = `/* * This file is auto-generated! Do not modify it directly. * To re-generate run 'make build' @@ -13,4 +12,4 @@ import { FLIPPED_ALIAS_KEYS } from "../../definitions";\n\n`; }); return output; -}; +} diff --git a/packages/babel-types/scripts/generators/docs.js b/packages/babel-types/scripts/generators/docs.js index 169894895b..18e536dd2f 100644 --- a/packages/babel-types/scripts/generators/docs.js +++ b/packages/babel-types/scripts/generators/docs.js @@ -1,10 +1,8 @@ -"use strict"; +import util from "util"; +import stringifyValidator from "../utils/stringifyValidator.js"; +import toFunctionName from "../utils/toFunctionName.js"; -const util = require("util"); -const stringifyValidator = require("../utils/stringifyValidator"); -const toFunctionName = require("../utils/toFunctionName"); - -const types = require("../../"); +import t from "../../lib/index.js"; const readme = [ `# @babel/types @@ -37,17 +35,13 @@ const customTypes = { key: "if computed then `Expression` else `Identifier | Literal`", }, }; -Object.keys(types.BUILDER_KEYS) +Object.keys(t.BUILDER_KEYS) .sort() .forEach(function (key) { readme.push("### " + key[0].toLowerCase() + key.substr(1)); readme.push("```javascript"); readme.push( - "t." + - toFunctionName(key) + - "(" + - types.BUILDER_KEYS[key].join(", ") + - ")" + "t." + toFunctionName(key) + "(" + t.BUILDER_KEYS[key].join(", ") + ")" ); readme.push("```"); readme.push(""); @@ -59,10 +53,10 @@ Object.keys(types.BUILDER_KEYS) "(node, opts)`." ); readme.push(""); - if (types.ALIAS_KEYS[key] && types.ALIAS_KEYS[key].length) { + if (t.ALIAS_KEYS[key] && t.ALIAS_KEYS[key].length) { readme.push( "Aliases: " + - types.ALIAS_KEYS[key] + t.ALIAS_KEYS[key] .map(function (key) { return "`" + key + "`"; }) @@ -70,19 +64,19 @@ Object.keys(types.BUILDER_KEYS) ); readme.push(""); } - Object.keys(types.NODE_FIELDS[key]) + Object.keys(t.NODE_FIELDS[key]) .sort(function (fieldA, fieldB) { - const indexA = types.BUILDER_KEYS[key].indexOf(fieldA); - const indexB = types.BUILDER_KEYS[key].indexOf(fieldB); + const indexA = t.BUILDER_KEYS[key].indexOf(fieldA); + const indexB = t.BUILDER_KEYS[key].indexOf(fieldB); if (indexA === indexB) return fieldA < fieldB ? -1 : 1; if (indexA === -1) return 1; if (indexB === -1) return -1; return indexA - indexB; }) .forEach(function (field) { - const defaultValue = types.NODE_FIELDS[key][field].default; + const defaultValue = t.NODE_FIELDS[key][field].default; const fieldDescription = ["`" + field + "`"]; - const validator = types.NODE_FIELDS[key][field].validate; + const validator = t.NODE_FIELDS[key][field].validate; if (customTypes[key] && customTypes[key][field]) { fieldDescription.push(`: ${customTypes[key][field]}`); } else if (validator) { @@ -99,11 +93,11 @@ Object.keys(types.BUILDER_KEYS) } } } - if (defaultValue !== null || types.NODE_FIELDS[key][field].optional) { + if (defaultValue !== null || t.NODE_FIELDS[key][field].optional) { fieldDescription.push( " (default: `" + util.inspect(defaultValue) + "`" ); - if (types.BUILDER_KEYS[key].indexOf(field) < 0) { + if (t.BUILDER_KEYS[key].indexOf(field) < 0) { fieldDescription.push(", excluded from builder function"); } fieldDescription.push(")"); diff --git a/packages/babel-types/scripts/generators/flow.js b/packages/babel-types/scripts/generators/flow.js index 8a0a7b2635..7fabcc67c5 100644 --- a/packages/babel-types/scripts/generators/flow.js +++ b/packages/babel-types/scripts/generators/flow.js @@ -1,8 +1,6 @@ -"use strict"; - -const t = require("../../"); -const stringifyValidator = require("../utils/stringifyValidator"); -const toFunctionName = require("../utils/toFunctionName"); +import t from "../../lib/index.js"; +import stringifyValidator from "../utils/stringifyValidator.js"; +import toFunctionName from "../utils/toFunctionName.js"; const NODE_PREFIX = "BabelNode"; diff --git a/packages/babel-types/scripts/generators/typescript-legacy.js b/packages/babel-types/scripts/generators/typescript-legacy.js index a77040681b..40da48f4e7 100644 --- a/packages/babel-types/scripts/generators/typescript-legacy.js +++ b/packages/babel-types/scripts/generators/typescript-legacy.js @@ -1,8 +1,6 @@ -"use strict"; - -const t = require("../../lib"); -const stringifyValidator = require("../utils/stringifyValidator"); -const toFunctionName = require("../utils/toFunctionName"); +import t from "../../lib/index.js"; +import stringifyValidator from "../utils/stringifyValidator.js"; +import toFunctionName from "../utils/toFunctionName.js"; let code = `// NOTE: This file is autogenerated. Do not modify. // See packages/babel-types/scripts/generators/typescript-legacy.js for script used. diff --git a/packages/babel-types/scripts/generators/validators.js b/packages/babel-types/scripts/generators/validators.js index c63d447bcd..acd6da6575 100644 --- a/packages/babel-types/scripts/generators/validators.js +++ b/packages/babel-types/scripts/generators/validators.js @@ -1,5 +1,4 @@ -"use strict"; -const definitions = require("../../lib/definitions"); +import definitions from "../../lib/definitions/index.js"; const has = Function.call.bind(Object.prototype.hasOwnProperty); @@ -62,7 +61,7 @@ function addIsHelper(type, aliasKeys, deprecated) { `; } -module.exports = function generateValidators() { +export default function generateValidators() { let output = `/* * This file is auto-generated! Do not modify it directly. * To re-generate run 'make build' @@ -85,4 +84,4 @@ import type * as t from "../..";\n\n`; }); return output; -}; +} diff --git a/packages/babel-types/scripts/package.json b/packages/babel-types/scripts/package.json new file mode 100644 index 0000000000..5ffd9800b9 --- /dev/null +++ b/packages/babel-types/scripts/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/packages/babel-types/scripts/utils/formatBuilderName.js b/packages/babel-types/scripts/utils/formatBuilderName.js index 621c468219..f00a3c4a61 100644 --- a/packages/babel-types/scripts/utils/formatBuilderName.js +++ b/packages/babel-types/scripts/utils/formatBuilderName.js @@ -1,10 +1,8 @@ -"use strict"; - const toLowerCase = Function.call.bind("".toLowerCase); -module.exports = function formatBuilderName(type) { +export default function formatBuilderName(type) { // FunctionExpression -> functionExpression // JSXIdentifier -> jsxIdentifier // V8IntrinsicIdentifier -> v8IntrinsicIdentifier return type.replace(/^([A-Z](?=[a-z0-9])|[A-Z]+(?=[A-Z]))/, toLowerCase); -}; +} diff --git a/packages/babel-types/scripts/utils/lowerFirst.js b/packages/babel-types/scripts/utils/lowerFirst.js index 9e7b0cee51..012f252a7f 100644 --- a/packages/babel-types/scripts/utils/lowerFirst.js +++ b/packages/babel-types/scripts/utils/lowerFirst.js @@ -1,4 +1,3 @@ -"use strict"; -module.exports = function lowerFirst(string) { +export default function lowerFirst(string) { return string[0].toLowerCase() + string.slice(1); -}; +} diff --git a/packages/babel-types/scripts/utils/stringifyValidator.js b/packages/babel-types/scripts/utils/stringifyValidator.js index 2ea1e80357..4b8d29c12c 100644 --- a/packages/babel-types/scripts/utils/stringifyValidator.js +++ b/packages/babel-types/scripts/utils/stringifyValidator.js @@ -1,4 +1,4 @@ -module.exports = function stringifyValidator(validator, nodePrefix) { +export default function stringifyValidator(validator, nodePrefix) { if (validator === undefined) { return "any"; } @@ -55,7 +55,7 @@ module.exports = function stringifyValidator(validator, nodePrefix) { } return ["any"]; -}; +} /** * Heuristic to decide whether or not the given type is a value type (eg. "null") diff --git a/packages/babel-types/scripts/utils/toFunctionName.js b/packages/babel-types/scripts/utils/toFunctionName.js index 627c9a7d8f..2b645780ec 100644 --- a/packages/babel-types/scripts/utils/toFunctionName.js +++ b/packages/babel-types/scripts/utils/toFunctionName.js @@ -1,4 +1,4 @@ -module.exports = function toFunctionName(typeName) { +export default function toFunctionName(typeName) { const _ = typeName.replace(/^TS/, "ts").replace(/^JSX/, "jsx"); return _.slice(0, 1).toLowerCase() + _.slice(1); -}; +} diff --git a/scripts/generators/readmes.js b/scripts/generators/readmes.js index 07c358cbc1..a52041ac57 100644 --- a/scripts/generators/readmes.js +++ b/scripts/generators/readmes.js @@ -5,8 +5,11 @@ * This script write the link to the website in every READMEs. */ -const { join } = require("path"); -const { readdirSync, writeFileSync } = require("fs"); +import { join } from "path"; +import { readdirSync, writeFileSync } from "fs"; +import { createRequire } from "url"; + +const require = createRequire(import.meta.url); const cwd = process.cwd(); diff --git a/scripts/generators/tsconfig.js b/scripts/generators/tsconfig.js index 1409cac9ac..eee32f516d 100644 --- a/scripts/generators/tsconfig.js +++ b/scripts/generators/tsconfig.js @@ -1,9 +1,14 @@ -"use strict"; +import path from "path"; +import fs from "fs"; +import { createRequire } from "module"; +import { fileURLToPath } from "url"; -const path = require("path"); -const fs = require("fs"); +const require = createRequire(import.meta.url); -const root = path.resolve(__dirname, "../../"); +const root = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "../../" +); function getTsPkgs(subRoot) { return fs diff --git a/scripts/integration-tests/utils/bump-babel-dependencies.js b/scripts/integration-tests/utils/bump-babel-dependencies.js index f7509dcf63..528c7a9de2 100644 --- a/scripts/integration-tests/utils/bump-babel-dependencies.js +++ b/scripts/integration-tests/utils/bump-babel-dependencies.js @@ -1,5 +1,6 @@ -const fs = require("fs"); -const path = require("path"); +import fs from "fs"; +import path from "path"; + const cwd = process.cwd(); const packageJSONPath = path.resolve(cwd, "./package.json"); const content = JSON.parse(fs.readFileSync(packageJSONPath)); diff --git a/scripts/package.json b/scripts/package.json new file mode 100644 index 0000000000..5ffd9800b9 --- /dev/null +++ b/scripts/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/scripts/parser-tests/flow/index.js b/scripts/parser-tests/flow/index.js index af60022d7b..7b7e8a0b0c 100644 --- a/scripts/parser-tests/flow/index.js +++ b/scripts/parser-tests/flow/index.js @@ -1,7 +1,10 @@ -const fs = require("fs").promises; -const path = require("path"); -const merge = require("mergeiterator"); -const TestRunner = require("../utils/parser-test-runner"); +import fs from "fs/promises"; +import path from "path"; +import { fileURLToPath } from "url"; +import merge from "mergeiterator"; +import TestRunner from "../utils/parser-test-runner.js"; + +const dirname = path.dirname(fileURLToPath(import.meta.url)); const flowOptionsMapping = { esproposal_class_instance_fields: "classProperties", @@ -88,8 +91,8 @@ async function* loadTests(root) { } const runner = new TestRunner({ - testDir: path.join(__dirname, "../../../build/flow/src/parser/test/flow"), - allowlist: path.join(__dirname, "allowlist.txt"), + testDir: path.join(dirname, "../../../build/flow/src/parser/test/flow"), + allowlist: path.join(dirname, "allowlist.txt"), shouldUpdate: process.argv.includes("--update-allowlist"), async *getTests() { diff --git a/scripts/parser-tests/test262/index.js b/scripts/parser-tests/test262/index.js index 9fe8141b9e..3c4d1856ad 100644 --- a/scripts/parser-tests/test262/index.js +++ b/scripts/parser-tests/test262/index.js @@ -1,6 +1,9 @@ -const path = require("path"); -const TestStream = require("test262-stream"); -const TestRunner = require("../utils/parser-test-runner"); +import path from "path"; +import { fileURLToPath } from "url"; +import TestStream from "test262-stream"; +import TestRunner from "../utils/parser-test-runner.js"; + +const dirname = path.dirname(fileURLToPath(import.meta.url)); const ignoredFeatures = [ "__getter__", @@ -163,8 +166,8 @@ function* getPlugins(features) { } const runner = new TestRunner({ - testDir: path.join(__dirname, "../../../build/test262"), - allowlist: path.join(__dirname, "allowlist.txt"), + testDir: path.join(dirname, "../../../build/test262"), + allowlist: path.join(dirname, "allowlist.txt"), logInterval: 500, shouldUpdate: process.argv.includes("--update-allowlist"), diff --git a/scripts/parser-tests/typescript/error-codes.js b/scripts/parser-tests/typescript/error-codes.js index 16ce4eb71c..8274005ce3 100644 --- a/scripts/parser-tests/typescript/error-codes.js +++ b/scripts/parser-tests/typescript/error-codes.js @@ -8,7 +8,7 @@ Note that babel-parser should not throw for the TypeChecking Diagnostics The commented out diagnostic codes will introduce false positive cases that should be addressed in separate PRs. */ -module.exports = [ +export default [ // "TS1005", // '{0}' expected. "TS1009", // Trailing comma not allowed. "TS1014", // A rest parameter must be last in a parameter list. diff --git a/scripts/parser-tests/typescript/index.js b/scripts/parser-tests/typescript/index.js index 36bd057cc9..52813b1658 100644 --- a/scripts/parser-tests/typescript/index.js +++ b/scripts/parser-tests/typescript/index.js @@ -1,8 +1,11 @@ -const path = require("path"); -const fs = require("fs").promises; -const ts = require("../../../build/typescript"); -const TestRunner = require("../utils/parser-test-runner"); -const parsingErrorCodes = require("./error-codes"); +import path from "path"; +import fs from "fs/promises"; +import { fileURLToPath } from "url"; +import ts from "../../../build/typescript/lib/typescript.js"; +import TestRunner from "../utils/parser-test-runner.js"; +import parsingErrorCodes from "./error-codes.js"; + +const dirname = path.dirname(fileURLToPath(import.meta.url)); async function* loadTests(dir) { const names = await fs.readdir(dir); @@ -21,7 +24,7 @@ const plugins = [ "dynamicImport", ]; -const TSTestsPath = path.join(__dirname, "../../../build/typescript/tests"); +const TSTestsPath = path.join(dirname, "../../../build/typescript/tests"); // Check if the baseline errors contain the codes that should also be thrown from babel-parser async function baselineContainsParserErrorCodes(testName) { @@ -45,7 +48,7 @@ async function baselineContainsParserErrorCodes(testName) { const runner = new TestRunner({ testDir: path.join(TSTestsPath, "./cases/compiler"), - allowlist: path.join(__dirname, "allowlist.txt"), + allowlist: path.join(dirname, "allowlist.txt"), logInterval: 50, shouldUpdate: process.argv.includes("--update-allowlist"), diff --git a/scripts/parser-tests/utils/parser-test-runner.js b/scripts/parser-tests/utils/parser-test-runner.js index 61b3ad16ef..79e235b48b 100644 --- a/scripts/parser-tests/utils/parser-test-runner.js +++ b/scripts/parser-tests/utils/parser-test-runner.js @@ -1,8 +1,6 @@ -"use strict"; - -const fs = require("fs").promises; -const chalk = require("chalk"); -const { parse: parser } = require("../../../packages/babel-parser"); +import fs from "fs/promises"; +import chalk from "chalk"; +import { parse as parser } from "../../../packages/babel-parser/lib/index.js"; const dot = chalk.gray("."); @@ -234,4 +232,4 @@ class TestRunner { } } -module.exports = exports = TestRunner; +export default TestRunner; diff --git a/scripts/rollup-plugin-babel-source.js b/scripts/rollup-plugin-babel-source.js index 7f4b794c37..5f4fbc49a7 100644 --- a/scripts/rollup-plugin-babel-source.js +++ b/scripts/rollup-plugin-babel-source.js @@ -1,20 +1,27 @@ -const path = require("path"); -const fs = require("fs"); -const dirname = path.join(__dirname, ".."); +import path from "path"; +import fs from "fs"; +import { fileURLToPath } from "url"; +import { createRequire } from "module"; + +const require = createRequire(import.meta.url); +const monorepoRoot = path.join( + path.dirname(fileURLToPath(import.meta.url)), + ".." +); const BABEL_SRC_REGEXP = path.sep === "/" ? /packages\/(babel-[^/]+)\/src\// : /packages\\(babel-[^\\]+)\\src\\/; -module.exports = function () { +export default function () { return { name: "babel-source", load(id) { const matches = id.match(BABEL_SRC_REGEXP); if (matches) { // check if browser field exists for this file and replace - const packageFolder = path.join(dirname, "packages", matches[1]); + const packageFolder = path.join(monorepoRoot, "packages", matches[1]); const packageJson = require(path.join(packageFolder, "package.json")); if ( @@ -46,7 +53,7 @@ module.exports = function () { resolveId(importee) { if (importee === "@babel/runtime/regenerator") { return path.join( - dirname, + monorepoRoot, "packages", "babel-runtime", "regenerator", @@ -61,7 +68,7 @@ module.exports = function () { const { pkg, internal } = matches.groups; // resolve babel package names to their src index file - const packageFolder = path.join(dirname, "packages", `babel-${pkg}`); + const packageFolder = path.join(monorepoRoot, "packages", `babel-${pkg}`); let packageJsonSource; try { @@ -98,4 +105,4 @@ module.exports = function () { } }, }; -}; +} diff --git a/scripts/utils/formatCode.js b/scripts/utils/formatCode.js index 0f14044016..ad42bde589 100644 --- a/scripts/utils/formatCode.js +++ b/scripts/utils/formatCode.js @@ -1,22 +1,9 @@ -"use strict"; +import prettier from "prettier"; -// TODO: Remove this `if` in Babel 8 -// Prettier only supports Node.js 10+, so we can fallback to not formatting -// o CI on older Node.js versions +export default function formatCode(code, filename) { + const prettierConfig = prettier.resolveConfig.sync(filename); + prettierConfig.filepath = filename; + prettierConfig.parser = filename.endsWith(".ts") ? "babel-ts" : "babel"; -if (process.env.CI && parseInt(process.versions.node, 10) < 10) { - module.exports = function formatCode(code) { - return code; - }; -} else { - const prettier = require("prettier"); - - module.exports = function formatCode(code, filename) { - filename = filename || __filename; - const prettierConfig = prettier.resolveConfig.sync(filename); - prettierConfig.filepath = filename; - prettierConfig.parser = filename.endsWith(".ts") ? "babel-ts" : "babel"; - - return prettier.format(code, prettierConfig); - }; + return prettier.format(code, prettierConfig); } diff --git a/test/esm/babel-runtime-corejs3.mjs b/test/esm/babel-runtime-corejs3.js similarity index 100% rename from test/esm/babel-runtime-corejs3.mjs rename to test/esm/babel-runtime-corejs3.js diff --git a/test/esm/babel-runtime.mjs b/test/esm/babel-runtime.js similarity index 100% rename from test/esm/babel-runtime.mjs rename to test/esm/babel-runtime.js diff --git a/test/esm/index.mjs b/test/esm/index.js similarity index 62% rename from test/esm/index.mjs rename to test/esm/index.js index 136eaeebb3..d4c33fc22c 100644 --- a/test/esm/index.mjs +++ b/test/esm/index.js @@ -1,6 +1,6 @@ -import babelRuntimeTestcases from "./babel-runtime.mjs"; -import babelRuntimeCorejs3Testcases from "./babel-runtime-corejs3.mjs"; -import testRunner from "./test-runner.mjs"; +import babelRuntimeTestcases from "./babel-runtime.js"; +import babelRuntimeCorejs3Testcases from "./babel-runtime-corejs3.js"; +import testRunner from "./test-runner.js"; (async () => { await testRunner(babelRuntimeTestcases); diff --git a/test/esm/package.json b/test/esm/package.json index fffd18db4b..916edd5340 100644 --- a/test/esm/package.json +++ b/test/esm/package.json @@ -2,7 +2,7 @@ "name": "@babel/test-esm", "private": true, "type": "module", - "exports": "./index.mjs", + "exports": "./index.js", "devDependencies": { "@babel/runtime": "workspace:*", "@babel/runtime-corejs3": "workspace:*", diff --git a/test/esm/test-runner.mjs b/test/esm/test-runner.js similarity index 100% rename from test/esm/test-runner.mjs rename to test/esm/test-runner.js