Use native ESM for dev scripts (#12296)

Co-authored-by: Nicolò Ribaudo <nicolo.ribaudo@gmail.com>
This commit is contained in:
Karan Sapolia 2021-01-30 23:06:21 +05:30 committed by GitHub
parent f8fe8eaab1
commit b63be942ce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
39 changed files with 205 additions and 193 deletions

View File

@ -1,5 +1,6 @@
{ {
"buildCommand": "codesandbox:build", "buildCommand": "codesandbox:build",
"sandboxes": ["7s08o", "vhm64"], "sandboxes": ["7s08o", "vhm64"],
"packages": ["packages/*"] "packages": ["packages/*"],
"node": "14"
} }

View File

@ -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: "." }],
},
},
], ],
}; };

View File

@ -65,8 +65,9 @@ jobs:
name: Build Babel Artifacts name: Build Babel Artifacts
needs: prepare-yarn-cache needs: prepare-yarn-cache
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: # Yarn PnP does not support native ESM yet (https://github.com/yarnpkg/berry/issues/638)
YARN_NODE_LINKER: pnp # use pnp linker for better linking performance and stricter checks # env:
# YARN_NODE_LINKER: pnp # use pnp linker for better linking performance and stricter checks
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v2 uses: actions/checkout@v2

View File

@ -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"); import plumber from "gulp-plumber";
const through = require("through2"); import through from "through2";
const chalk = require("chalk"); import chalk from "chalk";
const newer = require("gulp-newer"); import newer from "gulp-newer";
const babel = require("gulp-babel"); import babel from "gulp-babel";
const camelCase = require("lodash/camelCase"); import camelCase from "lodash/camelCase.js";
const fancyLog = require("fancy-log"); import fancyLog from "fancy-log";
const filter = require("gulp-filter"); import filter from "gulp-filter";
const gulp = require("gulp"); import gulp from "gulp";
const path = require("path"); import { rollup } from "rollup";
const fs = require("fs"); import { babel as rollupBabel } from "@rollup/plugin-babel";
const rollup = require("rollup"); import rollupCommonJs from "@rollup/plugin-commonjs";
const rollupBabel = require("@rollup/plugin-babel").default; import rollupJson from "@rollup/plugin-json";
const rollupBabelSource = require("./scripts/rollup-plugin-babel-source"); import rollupNodePolyfills from "rollup-plugin-node-polyfills";
const rollupCommonJs = require("@rollup/plugin-commonjs"); import rollupNodeResolve from "@rollup/plugin-node-resolve";
const rollupJson = require("@rollup/plugin-json"); import rollupReplace from "@rollup/plugin-replace";
const rollupNodePolyfills = require("rollup-plugin-node-polyfills"); import { terser as rollupTerser } from "rollup-plugin-terser";
const rollupNodeResolve = require("@rollup/plugin-node-resolve").default; import _rollupDts from "rollup-plugin-dts";
const rollupReplace = require("@rollup/plugin-replace"); const { default: rollupDts } = _rollupDts;
const { terser: rollupTerser } = require("rollup-plugin-terser");
const { default: rollupDts } = require("rollup-plugin-dts"); 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 defaultPackagesGlob = "./@(codemods|packages|eslint)/*";
const defaultSourcesGlob = `${defaultPackagesGlob}/src/**/{*.js,!(*.d).ts}`; const defaultSourcesGlob = `${defaultPackagesGlob}/src/**/{*.js,!(*.d).ts}`;
@ -92,15 +99,16 @@ function rename(fn) {
* @param {string} message * @param {string} message
*/ */
function generateHelpers(generator, dest, filename, message) { function generateHelpers(generator, dest, filename, message) {
const formatCode = require("./scripts/utils/formatCode");
const stream = gulp const stream = gulp
.src(".", { base: __dirname }) .src(".", { base: monorepoRoot })
.pipe(errorsLogger()) .pipe(errorsLogger())
.pipe( .pipe(
through.obj(function (file, enc, callback) { through.obj(async (file, enc, callback) => {
const { default: generateCode } = await import(generator);
file.path = filename; file.path = filename;
file.contents = Buffer.from( file.contents = Buffer.from(
formatCode(require(generator)(filename), dest + file.path) formatCode(generateCode(filename), dest + file.path)
); );
fancyLog(`${chalk.green("✔")} Generated ${message}`); fancyLog(`${chalk.green("✔")} Generated ${message}`);
callback(null, file); callback(null, file);
@ -119,7 +127,7 @@ function generateHelpers(generator, dest, filename, message) {
*/ */
async function generateTypeHelpers(helperKind, filename = "index.ts") { async function generateTypeHelpers(helperKind, filename = "index.ts") {
return generateHelpers( return generateHelpers(
`./packages/babel-types/scripts/generators/${helperKind}`, `./packages/babel-types/scripts/generators/${helperKind}.js`,
`./packages/babel-types/src/${helperKind}/generated/`, `./packages/babel-types/src/${helperKind}/generated/`,
filename, filename,
`@babel/types -> ${helperKind}` `@babel/types -> ${helperKind}`
@ -133,7 +141,7 @@ async function generateTypeHelpers(helperKind, filename = "index.ts") {
*/ */
async function generateTraverseHelpers(helperKind) { async function generateTraverseHelpers(helperKind) {
return generateHelpers( return generateHelpers(
`./packages/babel-traverse/scripts/generators/${helperKind}`, `./packages/babel-traverse/scripts/generators/${helperKind}.js`,
`./packages/babel-traverse/src/path/generated/`, `./packages/babel-traverse/src/path/generated/`,
`${helperKind}.ts`, `${helperKind}.ts`,
`@babel/traverse -> ${helperKind}` `@babel/traverse -> ${helperKind}`
@ -142,9 +150,8 @@ async function generateTraverseHelpers(helperKind) {
function generateStandalone() { function generateStandalone() {
const dest = "./packages/babel-standalone/src/generated/"; const dest = "./packages/babel-standalone/src/generated/";
const formatCode = require("./scripts/utils/formatCode");
return gulp return gulp
.src(babelStandalonePluginConfigGlob, { base: __dirname }) .src(babelStandalonePluginConfigGlob, { base: monorepoRoot })
.pipe( .pipe(
through.obj((file, enc, callback) => { through.obj((file, enc, callback) => {
fancyLog("Generating @babel/standalone files"); fancyLog("Generating @babel/standalone files");
@ -190,7 +197,7 @@ function finish(stream) {
} }
function getFiles(glob, { include, exclude }) { function getFiles(glob, { include, exclude }) {
let stream = gulp.src(glob, { base: __dirname }); let stream = gulp.src(glob, { base: monorepoRoot });
if (exclude) { if (exclude) {
const filters = exclude.map(p => `!**/${p}/**`); const filters = exclude.map(p => `!**/${p}/**`);
@ -206,7 +213,7 @@ function getFiles(glob, { include, exclude }) {
} }
function buildBabel(exclude) { function buildBabel(exclude) {
const base = __dirname; const base = monorepoRoot;
return getFiles(defaultSourcesGlob, { return getFiles(defaultSourcesGlob, {
exclude: exclude && exclude.map(p => p.src), exclude: exclude && exclude.map(p => p.src),
@ -259,7 +266,7 @@ function buildRollup(packages, targetBrowsers) {
} }
const input = getIndexFromPackage(src); const input = getIndexFromPackage(src);
fancyLog(`Compiling '${chalk.cyan(input)}' with rollup ...`); fancyLog(`Compiling '${chalk.cyan(input)}' with rollup ...`);
const bundle = await rollup.rollup({ const bundle = await rollup({
input, input,
external, external,
onwarn(warning, warn) { onwarn(warning, warn) {
@ -352,7 +359,7 @@ function buildRollupDts(packages) {
packages.map(async packageName => { packages.map(async packageName => {
const input = `${packageName}/lib/index.d.ts`; const input = `${packageName}/lib/index.d.ts`;
fancyLog(`Bundling '${chalk.cyan(input)}' with rollup ...`); fancyLog(`Bundling '${chalk.cyan(input)}' with rollup ...`);
const bundle = await rollup.rollup({ const bundle = await rollup({
input, input,
plugins: [rollupDts()], plugins: [rollupDts()],
}); });
@ -378,7 +385,7 @@ function removeDts(exclude) {
function copyDts(packages) { function copyDts(packages) {
return getFiles(`${defaultPackagesGlob}/src/**/*.d.ts`, { include: packages }) return getFiles(`${defaultPackagesGlob}/src/**/*.d.ts`, { include: packages })
.pipe(rename(file => path.resolve(file.base, mapSrcToLib(file.relative)))) .pipe(rename(file => path.resolve(file.base, mapSrcToLib(file.relative))))
.pipe(gulp.dest(__dirname)); .pipe(gulp.dest(monorepoRoot));
} }
const libBundles = [ const libBundles = [

View File

@ -87,12 +87,12 @@ check-compat-data-ci:
$(MAKE) check-compat-data $(MAKE) check-compat-data
lint: 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: fix-json fix-js
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: fix-json:
$(YARN) prettier "{$(COMMA_SEPARATED_SOURCES)}/*/test/fixtures/**/options.json" --write --loglevel warn $(YARN) prettier "{$(COMMA_SEPARATED_SOURCES)}/*/test/fixtures/**/options.json" --write --loglevel warn

View File

@ -3,6 +3,7 @@
"version": "7.12.12", "version": "7.12.12",
"private": true, "private": true,
"license": "MIT", "license": "MIT",
"type": "commonjs",
"scripts": { "scripts": {
"bootstrap": "make bootstrap", "bootstrap": "make bootstrap",
"codesandbox:build": "make build-no-bundle", "codesandbox:build": "make build-no-bundle",
@ -11,7 +12,7 @@
"lint": "make lint", "lint": "make lint",
"test": "make test", "test": "make test",
"version": "yarn --immutable-cache && git add yarn.lock", "version": "yarn --immutable-cache && git add yarn.lock",
"test:esm": "node test/esm/index.mjs" "test:esm": "node test/esm/index.js"
}, },
"devDependencies": { "devDependencies": {
"@babel/cli": "^7.12.0", "@babel/cli": "^7.12.0",

View File

@ -1,7 +1,6 @@
"use strict"; import t from "@babel/types";
const t = require("@babel/types");
module.exports = function generateAsserts() { export default function generateAsserts() {
let output = `/* let output = `/*
* This file is auto-generated! Do not modify it directly. * This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build' * To re-generate run 'make build'
@ -12,7 +11,7 @@ import NodePath from "../index";
export interface NodePathAssetions {`; export interface NodePathAssetions {`;
for (const type of t.TYPES) { for (const type of [...t.TYPES].sort()) {
output += ` output += `
assert${type}( assert${type}(
opts?: object, opts?: object,
@ -23,4 +22,4 @@ export interface NodePathAssetions {`;
}`; }`;
return output; return output;
}; }

View File

@ -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"); export default function generateValidators() {
const virtualTypes = require("../../lib/path/lib/virtual-types");
const definitions = require("@babel/types/lib/definitions");
module.exports = function generateValidators() {
let output = `/* let output = `/*
* This file is auto-generated! Do not modify it directly. * This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build' * To re-generate run 'make build'
@ -16,7 +13,7 @@ import NodePath from "../index";
export interface NodePathValidators { export interface NodePathValidators {
`; `;
for (const type of t.TYPES) { for (const type of [...t.TYPES].sort()) {
output += `is${type}(opts?: object): this is NodePath<t.${type}>;`; output += `is${type}(opts?: object): this is NodePath<t.${type}>;`;
} }
@ -34,4 +31,4 @@ export interface NodePathValidators {
`; `;
return output; return output;
}; }

View File

@ -1,8 +1,6 @@
"use strict"; import virtualTypes from "../../lib/path/lib/virtual-types.js";
const virtualTypes = require("../../lib/path/lib/virtual-types"); export default function generateValidators() {
module.exports = function generateValidators() {
let output = `/* let output = `/*
* This file is auto-generated! Do not modify it directly. * This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build' * To re-generate run 'make build'
@ -23,4 +21,4 @@ export interface VirtualTypeAliases {
`; `;
return output; return output;
}; }

View File

@ -0,0 +1 @@
{ "type": "module" }

View File

@ -1,5 +1,4 @@
"use strict"; import definitions from "../../lib/definitions/index.js";
const definitions = require("../../lib/definitions");
function addAssertHelper(type) { function addAssertHelper(type) {
const result = const result =
@ -14,7 +13,7 @@ function addAssertHelper(type) {
`; `;
} }
module.exports = function generateAsserts() { export default function generateAsserts() {
let output = `/* let output = `/*
* This file is auto-generated! Do not modify it directly. * This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build' * To re-generate run 'make build'
@ -48,4 +47,4 @@ function assert(type: string, node: any, opts?: any): void {
}); });
return output; return output;
}; }

View File

@ -1,9 +1,7 @@
"use strict"; import t from "../../lib/index.js";
import stringifyValidator from "../utils/stringifyValidator.js";
const t = require("../../"); export default function generateAstTypes() {
const stringifyValidator = require("../utils/stringifyValidator");
module.exports = function generateAstTypes() {
let code = `// NOTE: This file is autogenerated. Do not modify. let code = `// NOTE: This file is autogenerated. Do not modify.
// See packages/babel-types/scripts/generators/ast-types.js for script used. // 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"; code += "}\n\n";
return code; return code;
}; }
function hasDefault(field) { function hasDefault(field) {
return field.default != null; return field.default != null;

View File

@ -1,10 +1,8 @@
"use strict"; import t from "../../lib/index.js";
const definitions = require("../../lib/definitions"); import definitions from "../../lib/definitions/index.js";
const formatBuilderName = require("../utils/formatBuilderName"); import formatBuilderName from "../utils/formatBuilderName.js";
const lowerFirst = require("../utils/lowerFirst"); import lowerFirst from "../utils/lowerFirst.js";
import stringifyValidator from "../utils/stringifyValidator.js";
const t = require("../../");
const stringifyValidator = require("../utils/stringifyValidator");
function areAllRemainingFieldsNullable(fieldName, fieldNames, fields) { function areAllRemainingFieldsNullable(fieldName, fieldNames, fields) {
const index = fieldNames.indexOf(fieldName); const index = fieldNames.indexOf(fieldName);
@ -73,11 +71,11 @@ function generateBuilderArgs(type) {
return args; return args;
} }
module.exports = function generateBuilders(kind) { export default function generateBuilders(kind) {
return kind === "uppercase.js" return kind === "uppercase.js"
? generateUppercaseBuilders() ? generateUppercaseBuilders()
: generateLowercaseBuilders(); : generateLowercaseBuilders();
}; }
function generateLowercaseBuilders() { function generateLowercaseBuilders() {
let output = `/* let output = `/*

View File

@ -1,7 +1,6 @@
"use strict"; import definitions from "../../lib/definitions/index.js";
const definitions = require("../../lib/definitions");
module.exports = function generateConstants() { export default function generateConstants() {
let output = `/* let output = `/*
* This file is auto-generated! Do not modify it directly. * This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build' * To re-generate run 'make build'
@ -13,4 +12,4 @@ import { FLIPPED_ALIAS_KEYS } from "../../definitions";\n\n`;
}); });
return output; return output;
}; }

View File

@ -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"); import t from "../../lib/index.js";
const stringifyValidator = require("../utils/stringifyValidator");
const toFunctionName = require("../utils/toFunctionName");
const types = require("../../");
const readme = [ const readme = [
`# @babel/types `# @babel/types
@ -37,17 +35,13 @@ const customTypes = {
key: "if computed then `Expression` else `Identifier | Literal`", key: "if computed then `Expression` else `Identifier | Literal`",
}, },
}; };
Object.keys(types.BUILDER_KEYS) Object.keys(t.BUILDER_KEYS)
.sort() .sort()
.forEach(function (key) { .forEach(function (key) {
readme.push("### " + key[0].toLowerCase() + key.substr(1)); readme.push("### " + key[0].toLowerCase() + key.substr(1));
readme.push("```javascript"); readme.push("```javascript");
readme.push( readme.push(
"t." + "t." + toFunctionName(key) + "(" + t.BUILDER_KEYS[key].join(", ") + ")"
toFunctionName(key) +
"(" +
types.BUILDER_KEYS[key].join(", ") +
")"
); );
readme.push("```"); readme.push("```");
readme.push(""); readme.push("");
@ -59,10 +53,10 @@ Object.keys(types.BUILDER_KEYS)
"(node, opts)`." "(node, opts)`."
); );
readme.push(""); readme.push("");
if (types.ALIAS_KEYS[key] && types.ALIAS_KEYS[key].length) { if (t.ALIAS_KEYS[key] && t.ALIAS_KEYS[key].length) {
readme.push( readme.push(
"Aliases: " + "Aliases: " +
types.ALIAS_KEYS[key] t.ALIAS_KEYS[key]
.map(function (key) { .map(function (key) {
return "`" + key + "`"; return "`" + key + "`";
}) })
@ -70,19 +64,19 @@ Object.keys(types.BUILDER_KEYS)
); );
readme.push(""); readme.push("");
} }
Object.keys(types.NODE_FIELDS[key]) Object.keys(t.NODE_FIELDS[key])
.sort(function (fieldA, fieldB) { .sort(function (fieldA, fieldB) {
const indexA = types.BUILDER_KEYS[key].indexOf(fieldA); const indexA = t.BUILDER_KEYS[key].indexOf(fieldA);
const indexB = types.BUILDER_KEYS[key].indexOf(fieldB); const indexB = t.BUILDER_KEYS[key].indexOf(fieldB);
if (indexA === indexB) return fieldA < fieldB ? -1 : 1; if (indexA === indexB) return fieldA < fieldB ? -1 : 1;
if (indexA === -1) return 1; if (indexA === -1) return 1;
if (indexB === -1) return -1; if (indexB === -1) return -1;
return indexA - indexB; return indexA - indexB;
}) })
.forEach(function (field) { .forEach(function (field) {
const defaultValue = types.NODE_FIELDS[key][field].default; const defaultValue = t.NODE_FIELDS[key][field].default;
const fieldDescription = ["`" + field + "`"]; 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]) { if (customTypes[key] && customTypes[key][field]) {
fieldDescription.push(`: ${customTypes[key][field]}`); fieldDescription.push(`: ${customTypes[key][field]}`);
} else if (validator) { } 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( fieldDescription.push(
" (default: `" + util.inspect(defaultValue) + "`" " (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(", excluded from builder function");
} }
fieldDescription.push(")"); fieldDescription.push(")");

View File

@ -1,8 +1,6 @@
"use strict"; import t from "../../lib/index.js";
import stringifyValidator from "../utils/stringifyValidator.js";
const t = require("../../"); import toFunctionName from "../utils/toFunctionName.js";
const stringifyValidator = require("../utils/stringifyValidator");
const toFunctionName = require("../utils/toFunctionName");
const NODE_PREFIX = "BabelNode"; const NODE_PREFIX = "BabelNode";

View File

@ -1,8 +1,6 @@
"use strict"; import t from "../../lib/index.js";
import stringifyValidator from "../utils/stringifyValidator.js";
const t = require("../../lib"); import toFunctionName from "../utils/toFunctionName.js";
const stringifyValidator = require("../utils/stringifyValidator");
const toFunctionName = require("../utils/toFunctionName");
let code = `// NOTE: This file is autogenerated. Do not modify. let code = `// NOTE: This file is autogenerated. Do not modify.
// See packages/babel-types/scripts/generators/typescript-legacy.js for script used. // See packages/babel-types/scripts/generators/typescript-legacy.js for script used.

View File

@ -1,5 +1,4 @@
"use strict"; import definitions from "../../lib/definitions/index.js";
const definitions = require("../../lib/definitions");
const has = Function.call.bind(Object.prototype.hasOwnProperty); 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 = `/* let output = `/*
* This file is auto-generated! Do not modify it directly. * This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build' * To re-generate run 'make build'
@ -85,4 +84,4 @@ import type * as t from "../..";\n\n`;
}); });
return output; return output;
}; }

View File

@ -0,0 +1 @@
{ "type": "module" }

View File

@ -1,10 +1,8 @@
"use strict";
const toLowerCase = Function.call.bind("".toLowerCase); const toLowerCase = Function.call.bind("".toLowerCase);
module.exports = function formatBuilderName(type) { export default function formatBuilderName(type) {
// FunctionExpression -> functionExpression // FunctionExpression -> functionExpression
// JSXIdentifier -> jsxIdentifier // JSXIdentifier -> jsxIdentifier
// V8IntrinsicIdentifier -> v8IntrinsicIdentifier // V8IntrinsicIdentifier -> v8IntrinsicIdentifier
return type.replace(/^([A-Z](?=[a-z0-9])|[A-Z]+(?=[A-Z]))/, toLowerCase); return type.replace(/^([A-Z](?=[a-z0-9])|[A-Z]+(?=[A-Z]))/, toLowerCase);
}; }

View File

@ -1,4 +1,3 @@
"use strict"; export default function lowerFirst(string) {
module.exports = function lowerFirst(string) {
return string[0].toLowerCase() + string.slice(1); return string[0].toLowerCase() + string.slice(1);
}; }

View File

@ -1,4 +1,4 @@
module.exports = function stringifyValidator(validator, nodePrefix) { export default function stringifyValidator(validator, nodePrefix) {
if (validator === undefined) { if (validator === undefined) {
return "any"; return "any";
} }
@ -55,7 +55,7 @@ module.exports = function stringifyValidator(validator, nodePrefix) {
} }
return ["any"]; return ["any"];
}; }
/** /**
* Heuristic to decide whether or not the given type is a value type (eg. "null") * Heuristic to decide whether or not the given type is a value type (eg. "null")

View File

@ -1,4 +1,4 @@
module.exports = function toFunctionName(typeName) { export default function toFunctionName(typeName) {
const _ = typeName.replace(/^TS/, "ts").replace(/^JSX/, "jsx"); const _ = typeName.replace(/^TS/, "ts").replace(/^JSX/, "jsx");
return _.slice(0, 1).toLowerCase() + _.slice(1); return _.slice(0, 1).toLowerCase() + _.slice(1);
}; }

View File

@ -5,8 +5,11 @@
* This script write the link to the website in every READMEs. * This script write the link to the website in every READMEs.
*/ */
const { join } = require("path"); import { join } from "path";
const { readdirSync, writeFileSync } = require("fs"); import { readdirSync, writeFileSync } from "fs";
import { createRequire } from "url";
const require = createRequire(import.meta.url);
const cwd = process.cwd(); const cwd = process.cwd();

View File

@ -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 require = createRequire(import.meta.url);
const fs = require("fs");
const root = path.resolve(__dirname, "../../"); const root = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../../"
);
function getTsPkgs(subRoot) { function getTsPkgs(subRoot) {
return fs return fs

View File

@ -1,5 +1,6 @@
const fs = require("fs"); import fs from "fs";
const path = require("path"); import path from "path";
const cwd = process.cwd(); const cwd = process.cwd();
const packageJSONPath = path.resolve(cwd, "./package.json"); const packageJSONPath = path.resolve(cwd, "./package.json");
const content = JSON.parse(fs.readFileSync(packageJSONPath)); const content = JSON.parse(fs.readFileSync(packageJSONPath));

1
scripts/package.json Normal file
View File

@ -0,0 +1 @@
{ "type": "module" }

View File

@ -1,7 +1,10 @@
const fs = require("fs").promises; import fs from "fs/promises";
const path = require("path"); import path from "path";
const merge = require("mergeiterator"); import { fileURLToPath } from "url";
const TestRunner = require("../utils/parser-test-runner"); import merge from "mergeiterator";
import TestRunner from "../utils/parser-test-runner.js";
const dirname = path.dirname(fileURLToPath(import.meta.url));
const flowOptionsMapping = { const flowOptionsMapping = {
esproposal_class_instance_fields: "classProperties", esproposal_class_instance_fields: "classProperties",
@ -88,8 +91,8 @@ async function* loadTests(root) {
} }
const runner = new TestRunner({ const runner = new TestRunner({
testDir: path.join(__dirname, "../../../build/flow/src/parser/test/flow"), testDir: path.join(dirname, "../../../build/flow/src/parser/test/flow"),
allowlist: path.join(__dirname, "allowlist.txt"), allowlist: path.join(dirname, "allowlist.txt"),
shouldUpdate: process.argv.includes("--update-allowlist"), shouldUpdate: process.argv.includes("--update-allowlist"),
async *getTests() { async *getTests() {

View File

@ -1,6 +1,9 @@
const path = require("path"); import path from "path";
const TestStream = require("test262-stream"); import { fileURLToPath } from "url";
const TestRunner = require("../utils/parser-test-runner"); import TestStream from "test262-stream";
import TestRunner from "../utils/parser-test-runner.js";
const dirname = path.dirname(fileURLToPath(import.meta.url));
const ignoredFeatures = [ const ignoredFeatures = [
"__getter__", "__getter__",
@ -163,8 +166,8 @@ function* getPlugins(features) {
} }
const runner = new TestRunner({ const runner = new TestRunner({
testDir: path.join(__dirname, "../../../build/test262"), testDir: path.join(dirname, "../../../build/test262"),
allowlist: path.join(__dirname, "allowlist.txt"), allowlist: path.join(dirname, "allowlist.txt"),
logInterval: 500, logInterval: 500,
shouldUpdate: process.argv.includes("--update-allowlist"), shouldUpdate: process.argv.includes("--update-allowlist"),

View File

@ -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. The commented out diagnostic codes will introduce false positive cases that should be addressed in separate PRs.
*/ */
module.exports = [ export default [
// "TS1005", // '{0}' expected. // "TS1005", // '{0}' expected.
"TS1009", // Trailing comma not allowed. "TS1009", // Trailing comma not allowed.
"TS1014", // A rest parameter must be last in a parameter list. "TS1014", // A rest parameter must be last in a parameter list.

View File

@ -1,8 +1,11 @@
const path = require("path"); import path from "path";
const fs = require("fs").promises; import fs from "fs/promises";
const ts = require("../../../build/typescript"); import { fileURLToPath } from "url";
const TestRunner = require("../utils/parser-test-runner"); import ts from "../../../build/typescript/lib/typescript.js";
const parsingErrorCodes = require("./error-codes"); 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) { async function* loadTests(dir) {
const names = await fs.readdir(dir); const names = await fs.readdir(dir);
@ -21,7 +24,7 @@ const plugins = [
"dynamicImport", "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 // Check if the baseline errors contain the codes that should also be thrown from babel-parser
async function baselineContainsParserErrorCodes(testName) { async function baselineContainsParserErrorCodes(testName) {
@ -45,7 +48,7 @@ async function baselineContainsParserErrorCodes(testName) {
const runner = new TestRunner({ const runner = new TestRunner({
testDir: path.join(TSTestsPath, "./cases/compiler"), testDir: path.join(TSTestsPath, "./cases/compiler"),
allowlist: path.join(__dirname, "allowlist.txt"), allowlist: path.join(dirname, "allowlist.txt"),
logInterval: 50, logInterval: 50,
shouldUpdate: process.argv.includes("--update-allowlist"), shouldUpdate: process.argv.includes("--update-allowlist"),

View File

@ -1,8 +1,6 @@
"use strict"; import fs from "fs/promises";
import chalk from "chalk";
const fs = require("fs").promises; import { parse as parser } from "../../../packages/babel-parser/lib/index.js";
const chalk = require("chalk");
const { parse: parser } = require("../../../packages/babel-parser");
const dot = chalk.gray("."); const dot = chalk.gray(".");
@ -234,4 +232,4 @@ class TestRunner {
} }
} }
module.exports = exports = TestRunner; export default TestRunner;

View File

@ -1,20 +1,27 @@
const path = require("path"); import path from "path";
const fs = require("fs"); import fs from "fs";
const dirname = path.join(__dirname, ".."); 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 = const BABEL_SRC_REGEXP =
path.sep === "/" path.sep === "/"
? /packages\/(babel-[^/]+)\/src\// ? /packages\/(babel-[^/]+)\/src\//
: /packages\\(babel-[^\\]+)\\src\\/; : /packages\\(babel-[^\\]+)\\src\\/;
module.exports = function () { export default function () {
return { return {
name: "babel-source", name: "babel-source",
load(id) { load(id) {
const matches = id.match(BABEL_SRC_REGEXP); const matches = id.match(BABEL_SRC_REGEXP);
if (matches) { if (matches) {
// check if browser field exists for this file and replace // 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")); const packageJson = require(path.join(packageFolder, "package.json"));
if ( if (
@ -46,7 +53,7 @@ module.exports = function () {
resolveId(importee) { resolveId(importee) {
if (importee === "@babel/runtime/regenerator") { if (importee === "@babel/runtime/regenerator") {
return path.join( return path.join(
dirname, monorepoRoot,
"packages", "packages",
"babel-runtime", "babel-runtime",
"regenerator", "regenerator",
@ -61,7 +68,7 @@ module.exports = function () {
const { pkg, internal } = matches.groups; const { pkg, internal } = matches.groups;
// resolve babel package names to their src index file // 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; let packageJsonSource;
try { try {
@ -98,4 +105,4 @@ module.exports = function () {
} }
}, },
}; };
}; }

View File

@ -1,22 +1,9 @@
"use strict"; import prettier from "prettier";
// TODO: Remove this `if` in Babel 8 export default function formatCode(code, filename) {
// Prettier only supports Node.js 10+, so we can fallback to not formatting
// o CI on older Node.js versions
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); const prettierConfig = prettier.resolveConfig.sync(filename);
prettierConfig.filepath = filename; prettierConfig.filepath = filename;
prettierConfig.parser = filename.endsWith(".ts") ? "babel-ts" : "babel"; prettierConfig.parser = filename.endsWith(".ts") ? "babel-ts" : "babel";
return prettier.format(code, prettierConfig); return prettier.format(code, prettierConfig);
};
} }

View File

@ -1,6 +1,6 @@
import babelRuntimeTestcases from "./babel-runtime.mjs"; import babelRuntimeTestcases from "./babel-runtime.js";
import babelRuntimeCorejs3Testcases from "./babel-runtime-corejs3.mjs"; import babelRuntimeCorejs3Testcases from "./babel-runtime-corejs3.js";
import testRunner from "./test-runner.mjs"; import testRunner from "./test-runner.js";
(async () => { (async () => {
await testRunner(babelRuntimeTestcases); await testRunner(babelRuntimeTestcases);

View File

@ -2,7 +2,7 @@
"name": "@babel/test-esm", "name": "@babel/test-esm",
"private": true, "private": true,
"type": "module", "type": "module",
"exports": "./index.mjs", "exports": "./index.js",
"devDependencies": { "devDependencies": {
"@babel/runtime": "workspace:*", "@babel/runtime": "workspace:*",
"@babel/runtime-corejs3": "workspace:*", "@babel/runtime-corejs3": "workspace:*",