diff --git a/packages/babel-helper-module-transforms/src/index.ts b/packages/babel-helper-module-transforms/src/index.ts index 5001699b619e..241dac12e110 100644 --- a/packages/babel-helper-module-transforms/src/index.ts +++ b/packages/babel-helper-module-transforms/src/index.ts @@ -27,7 +27,9 @@ import normalizeModuleAndLoadMetadata, { validateImportInteropOption, } from "./normalize-and-load-metadata"; import type { + ImportInterop, InteropType, + Lazy, ModuleMetadata, SourceModuleMetadata, } from "./normalize-and-load-metadata"; @@ -38,6 +40,22 @@ export type { PluginOptions } from "./get-module-name"; export { hasExports, isSideEffectImport, isModule, rewriteThis }; +export interface RewriteModuleStatementsAndPrepareHeaderOptions { + exportName?: string; + strict: boolean; + allowTopLevelThis?: boolean; + strictMode: boolean; + loose?: boolean; + importInterop?: ImportInterop; + noInterop?: boolean; + lazy?: Lazy; + esNamespaceOnly?: boolean; + filename: string | undefined; + constantReexports?: boolean | void; + enumerableModuleMeta?: boolean | void; + noIncompleteNsImportDetection?: boolean | void; +} + /** * Perform all of the generic ES6 module rewriting needed to handle initial * module processing. This function will rewrite the majority of the given @@ -63,21 +81,7 @@ export function rewriteModuleStatementsAndPrepareHeader( constantReexports = loose, enumerableModuleMeta = loose, noIncompleteNsImportDetection, - }: { - exportName?; - strict; - allowTopLevelThis?; - strictMode; - loose?; - importInterop?: "none" | "babel" | "node"; - noInterop?; - lazy?; - esNamespaceOnly?; - filename: string | undefined; - constantReexports?; - enumerableModuleMeta?; - noIncompleteNsImportDetection?: boolean; - }, + }: RewriteModuleStatementsAndPrepareHeaderOptions, ) { validateImportInteropOption(importInterop); assert(isModule(path), "Cannot process module statements in a script"); @@ -138,9 +142,10 @@ export function rewriteModuleStatementsAndPrepareHeader( * Flag a set of statements as hoisted above all else so that module init * statements all run before user code. */ -export function ensureStatementsHoisted(statements) { +export function ensureStatementsHoisted(statements: t.Statement[]) { // Force all of the header fields to be at the top of the file. statements.forEach(header => { + // @ts-ignore Fixme: handle _blockHoist property header._blockHoist = 3; }); } @@ -303,7 +308,7 @@ const buildReexportsFromMeta = ( */ function buildESModuleHeader( metadata: ModuleMetadata, - enumerableModuleMeta: boolean = false, + enumerableModuleMeta: boolean | void = false, ) { return ( enumerableModuleMeta @@ -321,7 +326,11 @@ function buildESModuleHeader( /** * Create a re-export initialization loop for a specific imported namespace. */ -function buildNamespaceReexport(metadata, namespace, constantReexports) { +function buildNamespaceReexport( + metadata: ModuleMetadata, + namespace: t.Identifier | t.CallExpression, + constantReexports: boolean | void, +) { return ( constantReexports ? template.statement` @@ -413,8 +422,8 @@ function buildExportNameListDeclaration( function buildExportInitializationStatements( programPath: NodePath, metadata: ModuleMetadata, - constantReexports: boolean = false, - noIncompleteNsImportDetection = false, + constantReexports: boolean | void = false, + noIncompleteNsImportDetection: boolean | void = false, ) { const initStatements: Array<[string, t.Statement | null]> = []; @@ -514,7 +523,11 @@ const InitTemplate = { default: template.expression`EXPORTS.NAME = VALUE`, }; -function buildInitStatement(metadata: ModuleMetadata, exportNames, initExpr) { +function buildInitStatement( + metadata: ModuleMetadata, + exportNames: string[], + initExpr: t.Expression, +) { const { stringSpecifiers, exportName: EXPORTS } = metadata; return expressionStatement( exportNames.reduce((acc, exportName) => { diff --git a/packages/babel-helper-module-transforms/src/normalize-and-load-metadata.ts b/packages/babel-helper-module-transforms/src/normalize-and-load-metadata.ts index bd2941fba21f..e4a263831784 100644 --- a/packages/babel-helper-module-transforms/src/normalize-and-load-metadata.ts +++ b/packages/babel-helper-module-transforms/src/normalize-and-load-metadata.ts @@ -28,6 +28,14 @@ export type InteropType = | "node-namespace" // Node.js interop for namespace or default+named imports | "none"; // No interop, or named-only imports +export type ImportInterop = + | "none" + | "babel" + | "node" + | ((source: string, filename?: string) => "none" | "babel" | "node"); + +export type Lazy = boolean | string[] | ((source: string) => boolean); + export interface SourceModuleMetadata { // A unique variable name to use for this namespace object. Centralized for simplicity. name: string; @@ -45,7 +53,7 @@ export interface SourceModuleMetadata { reexportAll: null | { loc: t.SourceLocation | undefined | null; }; - lazy?; + lazy?: Lazy; } export interface LocalExportMetadata { @@ -75,7 +83,7 @@ export function isSideEffectImport(source: SourceModuleMetadata) { export function validateImportInteropOption( importInterop: any, -): importInterop is "none" | "babel" | "node" | Function { +): importInterop is ImportInterop { if ( typeof importInterop !== "function" && importInterop !== "none" && @@ -90,8 +98,8 @@ export function validateImportInteropOption( } function resolveImportInterop( - importInterop, - source, + importInterop: ImportInterop, + source: string, filename: string | undefined, ) { if (typeof importInterop === "function") { @@ -113,6 +121,12 @@ export default function normalizeModuleAndLoadMetadata( lazy = false, esNamespaceOnly = false, filename, + }: { + importInterop: ImportInterop; + initializeReexports: boolean | void; + lazy: Lazy; + esNamespaceOnly: boolean; + filename: string; }, ): ModuleMetadata { if (!exportName) { @@ -219,8 +233,8 @@ function getModuleMetadata( initializeReexports, }: { // todo(flow-ts) changed from boolean, to match expected usage inside the function - lazy: boolean | string[] | Function; - initializeReexports: boolean; + lazy: boolean | string[] | ((source: string) => boolean); + initializeReexports: boolean | void; }, stringSpecifiers: Set, ) { @@ -231,7 +245,7 @@ function getModuleMetadata( ); const sourceData = new Map(); - const getData = sourceNode => { + const getData = (sourceNode: t.StringLiteral) => { const source = sourceNode.value; let data = sourceData.get(source); @@ -409,22 +423,26 @@ function getModuleMetadata( }; } +type ModuleBindingKind = "import" | "hoisted" | "block" | "var"; /** * Get metadata about local variables that are exported. */ function getLocalExportMetadata( programPath: NodePath, - initializeReexports: boolean, + initializeReexports: boolean | void, stringSpecifiers: Set, ): Map { const bindingKindLookup = new Map(); - programPath.get("body").forEach((child: any) => { - let kind; + programPath.get("body").forEach(child => { + let kind: ModuleBindingKind; if (child.isImportDeclaration()) { kind = "import"; } else { - if (child.isExportDefaultDeclaration()) child = child.get("declaration"); + if (child.isExportDefaultDeclaration()) { + // @ts-ignore + child = child.get("declaration"); + } if (child.isExportNamedDeclaration()) { if (child.node.declaration) { child = child.get("declaration"); @@ -460,7 +478,7 @@ function getLocalExportMetadata( }); const localMetadata = new Map(); - const getLocalMetadata = idPath => { + const getLocalMetadata = (idPath: NodePath) => { const localName = idPath.node.name; let metadata = localMetadata.get(localName); diff --git a/packages/babel-helper-module-transforms/src/rewrite-live-references.ts b/packages/babel-helper-module-transforms/src/rewrite-live-references.ts index 9ba5d3063182..33c7eb3af37b 100644 --- a/packages/babel-helper-module-transforms/src/rewrite-live-references.ts +++ b/packages/babel-helper-module-transforms/src/rewrite-live-references.ts @@ -27,12 +27,12 @@ import type { ModuleMetadata } from "./normalize-and-load-metadata"; interface RewriteReferencesVisitorState { exported: Map; metadata: ModuleMetadata; - requeueInParent: (path) => void; + requeueInParent: (path: NodePath) => void; scope: Scope; imported: Map; buildImportReference: ( - [source, importName, localName]: readonly [any, any, any], - identNode, + [source, importName, localName]: readonly [string, string, string], + identNode: t.Identifier | t.CallExpression | t.JSXIdentifier, ) => any; seen: WeakSet; } @@ -40,11 +40,11 @@ interface RewriteReferencesVisitorState { interface RewriteBindingInitVisitorState { exported: Map; metadata: ModuleMetadata; - requeueInParent: (path) => void; + requeueInParent: (path: NodePath) => void; scope: Scope; } -function isInType(path) { +function isInType(path: NodePath) { do { switch (path.parent.type) { case "TSTypeAnnotation": @@ -54,7 +54,13 @@ function isInType(path) { case "TypeAlias": return true; case "ExportSpecifier": - return path.parentPath.parent.exportKind === "type"; + return ( + ( + path.parentPath.parent as + | t.ExportDefaultDeclaration + | t.ExportNamedDeclaration + ).exportKind === "type" + ); default: if (path.parentPath.isStatement() || path.parentPath.isExpression()) { return false; @@ -69,7 +75,7 @@ export default function rewriteLiveReferences( ) { const imported = new Map(); const exported = new Map(); - const requeueInParent = path => { + const requeueInParent = (path: NodePath) => { // Manually re-queue `exports.default =` expressions so that the ES3 // transform has an opportunity to convert them. Ideally this would // happen automatically from the replaceWith above. See #4140 for @@ -127,7 +133,13 @@ export default function rewriteLiveReferences( const meta = metadata.source.get(source); if (localName) { - if (meta.lazy) identNode = callExpression(identNode, []); + if (meta.lazy) { + identNode = callExpression( + // @ts-expect-error Fixme: we should handle the case when identNode is a JSXIdentifier + identNode, + [], + ); + } return identNode; } @@ -203,9 +215,9 @@ const rewriteBindingInitVisitor: Visitor = { }; const buildBindingExportAssignmentExpression = ( - metadata, - exportNames, - localExpr, + metadata: ModuleMetadata, + exportNames: string[], + localExpr: t.Expression, ) => { return (exportNames || []).reduce((expr, exportName) => { // class Foo {} export { Foo, Foo as Bar }; @@ -225,7 +237,7 @@ const buildBindingExportAssignmentExpression = ( }, localExpr); }; -const buildImportThrow = localName => { +const buildImportThrow = (localName: string) => { return template.expression.ast` (function() { throw new Error('"' + '${localName}' + '" is read-only.'); @@ -403,7 +415,7 @@ const rewriteReferencesVisitor: Visitor = { const assignment = path.node; if (importData) { - assignment.left = buildImportReference(importData, assignment.left); + assignment.left = buildImportReference(importData, left.node); assignment.right = sequenceExpression([ assignment.right, @@ -437,7 +449,7 @@ const rewriteReferencesVisitor: Visitor = { // Complex ({a, b, c} = {}); export { a, c }; // => ({a, b, c} = {}), (exports.a = a, exports.c = c); - const items = []; + const items: t.Expression[] = []; programScopeIds.forEach(localName => { const exportedNames = exported.get(localName) || []; if (exportedNames.length > 0) { diff --git a/packages/babel-helper-module-transforms/src/rewrite-this.ts b/packages/babel-helper-module-transforms/src/rewrite-this.ts index 92d9dd233968..cfd6aa9c24a2 100644 --- a/packages/babel-helper-module-transforms/src/rewrite-this.ts +++ b/packages/babel-helper-module-transforms/src/rewrite-this.ts @@ -1,7 +1,6 @@ import environmentVisitor from "@babel/helper-environment-visitor"; import traverse from "@babel/traverse"; import { numericLiteral, unaryExpression } from "@babel/types"; -import type * as t from "@babel/types"; import type { NodePath, Visitor } from "@babel/traverse"; export default function rewriteThis(programPath: NodePath) { @@ -16,7 +15,7 @@ export default function rewriteThis(programPath: NodePath) { const rewriteThisVisitor: Visitor = traverse.visitors.merge([ environmentVisitor, { - ThisExpression(path: NodePath) { + ThisExpression(path) { path.replaceWith(unaryExpression("void", numericLiteral(0), true)); }, }, diff --git a/packages/babel-plugin-transform-modules-amd/src/index.ts b/packages/babel-plugin-transform-modules-amd/src/index.ts index a22064354549..04e20d9c779c 100644 --- a/packages/babel-plugin-transform-modules-amd/src/index.ts +++ b/packages/babel-plugin-transform-modules-amd/src/index.ts @@ -2,6 +2,7 @@ import { declare } from "@babel/helper-plugin-utils"; import { isModule, rewriteModuleStatementsAndPrepareHeader, + type RewriteModuleStatementsAndPrepareHeaderOptions, hasExports, isSideEffectImport, buildNamespaceInitStatements, @@ -12,33 +13,41 @@ import { import { template, types as t } from "@babel/core"; import { getImportSource } from "babel-plugin-dynamic-import-node/utils"; import type { PluginOptions } from "@babel/helper-module-transforms"; +import type { NodePath } from "@babel/traverse"; -const buildWrapper = template(` +const buildWrapper = template.statement(` define(MODULE_NAME, AMD_ARGUMENTS, function(IMPORT_NAMES) { }) `); -const buildAnonymousWrapper = template(` +const buildAnonymousWrapper = template.statement(` define(["require"], function(REQUIRE) { }) `); -function injectWrapper(path, wrapper) { +function injectWrapper( + path: NodePath, + wrapper: t.ExpressionStatement, +) { const { body, directives } = path.node; path.node.directives = []; path.node.body = []; - const amdWrapper = path.pushContainer("body", wrapper)[0]; - const amdFactory = amdWrapper - .get("expression.arguments") - .filter(arg => arg.isFunctionExpression())[0] - .get("body"); + const amdFactoryCall = ( + path.pushContainer("body", wrapper)[0] as NodePath + ).get("expression") as NodePath; + const amdFactoryCallArgs = amdFactoryCall.get("arguments"); + const amdFactory = ( + amdFactoryCallArgs[ + amdFactoryCallArgs.length - 1 + ] as NodePath + ).get("body") as NodePath; amdFactory.pushContainer("directives", directives); amdFactory.pushContainer("body", body); } export interface Options extends PluginOptions { allowTopLevelThis?: boolean; - importInterop?: "babel" | "node"; + importInterop?: RewriteModuleStatementsAndPrepareHeaderOptions["importInterop"]; loose?: boolean; noInterop?: boolean; strict?: boolean; @@ -107,7 +116,9 @@ export default declare((api, options: Options) => { if (requireId) { injectWrapper( path, - buildAnonymousWrapper({ REQUIRE: t.cloneNode(requireId) }), + buildAnonymousWrapper({ + REQUIRE: t.cloneNode(requireId), + }) as t.ExpressionStatement, ); } return; @@ -186,7 +197,7 @@ export default declare((api, options: Options) => { AMD_ARGUMENTS: t.arrayExpression(amdArgs), IMPORT_NAMES: importNames, - }), + }) as t.ExpressionStatement, ); }, }, diff --git a/packages/babel-plugin-transform-modules-commonjs/src/index.ts b/packages/babel-plugin-transform-modules-commonjs/src/index.ts index e3de86a846b6..d15f31c4e0a6 100644 --- a/packages/babel-plugin-transform-modules-commonjs/src/index.ts +++ b/packages/babel-plugin-transform-modules-commonjs/src/index.ts @@ -2,6 +2,7 @@ import { declare } from "@babel/helper-plugin-utils"; import { isModule, rewriteModuleStatementsAndPrepareHeader, + type RewriteModuleStatementsAndPrepareHeaderOptions, isSideEffectImport, buildNamespaceInitStatements, ensureStatementsHoisted, @@ -18,8 +19,8 @@ import { createDynamicImportTransform } from "babel-plugin-dynamic-import-node/u export interface Options extends PluginOptions { allowCommonJSExports?: boolean; allowTopLevelThis?: boolean; - importInterop?: "babel" | "node"; - lazy?: boolean | string[] | ((string) => boolean); + importInterop?: RewriteModuleStatementsAndPrepareHeaderOptions["importInterop"]; + lazy?: RewriteModuleStatementsAndPrepareHeaderOptions["lazy"]; loose?: boolean; mjsStrictNamespace?: boolean; noInterop?: boolean; @@ -74,7 +75,7 @@ export default declare((api, options: Options) => { throw new Error(`.mjsStrictNamespace must be a boolean, or undefined`); } - const getAssertion = localName => template.expression.ast` + const getAssertion = (localName: string) => template.expression.ast` (function(){ throw new Error( "The CommonJS '" + "${localName}" + "' variable is not available in ES6 modules." + @@ -236,7 +237,7 @@ export default declare((api, options: Options) => { t.stringLiteral(source), ]); - let header; + let header: t.Statement; if (isSideEffectImport(metadata)) { if (metadata.lazy) throw new Error("Assertion failure"); @@ -246,7 +247,7 @@ export default declare((api, options: Options) => { wrapInterop(path, loadExpr, metadata.interop) || loadExpr; if (metadata.lazy) { - header = template.ast` + header = template.statement.ast` function ${metadata.name}() { const data = ${init}; ${metadata.name} = function(){ return data; }; @@ -254,7 +255,7 @@ export default declare((api, options: Options) => { } `; } else { - header = template.ast` + header = template.statement.ast` var ${metadata.name} = ${init}; `; } diff --git a/packages/babel-plugin-transform-modules-systemjs/src/index.ts b/packages/babel-plugin-transform-modules-systemjs/src/index.ts index 19ff21f0e890..95b9dffed749 100644 --- a/packages/babel-plugin-transform-modules-systemjs/src/index.ts +++ b/packages/babel-plugin-transform-modules-systemjs/src/index.ts @@ -72,12 +72,18 @@ type PluginState = { stringSpecifiers: Set; }; +type ModuleMetadata = { + key: string; + imports: any[]; + exports: any[]; +}; + function constructExportCall( - path, - exportIdent, - exportNames, - exportValues, - exportStarTarget, + path: NodePath, + exportIdent: t.Identifier, + exportNames: string[], + exportValues: t.Expression[], + exportStarTarget: t.Identifier | null, stringSpecifiers: Set, ) { const statements = []; @@ -312,27 +318,31 @@ export default declare((api, options: Options) => { rewriteThis(path); } }, - exit(path: NodePath, state: PluginState) { + exit(path, state) { const scope = path.scope; const exportIdent = scope.generateUid("export"); const { contextIdent, stringSpecifiers } = state; - const exportMap = Object.create(null); - const modules = []; + const exportMap: Record = Object.create(null); + const modules: ModuleMetadata[] = []; const beforeBody = []; - const setters = []; - const sources = []; + const setters: t.Expression[] = []; + const sources: t.StringLiteral[] = []; const variableIds = []; const removedPaths = []; - function addExportName(key, val) { + function addExportName(key: string, val: string) { exportMap[key] = exportMap[key] || []; exportMap[key].push(val); } - function pushModule(source, key, specifiers) { - let module; + function pushModule( + source: string, + key: "imports" | "exports", + specifiers: t.ModuleSpecifier[] | t.ExportAllDeclaration, + ) { + let module: ModuleMetadata; modules.forEach(function (m) { if (m.key === source) { module = m; @@ -346,7 +356,7 @@ export default declare((api, options: Options) => { module[key] = module[key].concat(specifiers); } - function buildExportCall(name, val) { + function buildExportCall(name: string, val: t.Expression) { return t.expressionStatement( t.callExpression(t.identifier(exportIdent), [ t.stringLiteral(name), @@ -356,7 +366,7 @@ export default declare((api, options: Options) => { } const exportNames = []; - const exportValues = []; + const exportValues: t.Expression[] = []; const body = path.get("body"); @@ -391,9 +401,9 @@ export default declare((api, options: Options) => { pushModule(path.node.source.value, "exports", path.node); path.remove(); } else if (path.isExportDefaultDeclaration()) { - const declar = path.get("declaration"); - if (declar.isClassDeclaration()) { - const id = declar.node.id; + const declar = path.node.declaration; + if (t.isClassDeclaration(declar)) { + const id = declar.id; if (id) { exportNames.push("default"); exportValues.push(scope.buildUndefinedNode()); @@ -404,67 +414,66 @@ export default declare((api, options: Options) => { t.assignmentExpression( "=", t.cloneNode(id), - t.toExpression(declar.node), + t.toExpression(declar), ), ), ); } else { exportNames.push("default"); - exportValues.push(t.toExpression(declar.node)); + exportValues.push(t.toExpression(declar)); removedPaths.push(path); } - } else if (declar.isFunctionDeclaration()) { - const id = declar.node.id; + } else if (t.isFunctionDeclaration(declar)) { + const id = declar.id; if (id) { - beforeBody.push(declar.node); + beforeBody.push(declar); exportNames.push("default"); exportValues.push(t.cloneNode(id)); addExportName(id.name, "default"); } else { exportNames.push("default"); - exportValues.push(t.toExpression(declar.node)); + exportValues.push(t.toExpression(declar)); } removedPaths.push(path); } else { - path.replaceWith(buildExportCall("default", declar.node)); + path.replaceWith(buildExportCall("default", declar)); } } else if (path.isExportNamedDeclaration()) { - const declar = path.get("declaration"); + const declar = path.node.declaration; - if (declar.node) { + if (declar) { path.replaceWith(declar); - if (declar.isFunction()) { - const node = declar.node; - const name = node.id.name; + if (t.isFunction(declar)) { + const name = declar.id.name; addExportName(name, name); - beforeBody.push(node); + beforeBody.push(declar); exportNames.push(name); - exportValues.push(t.cloneNode(node.id)); + exportValues.push(t.cloneNode(declar.id)); removedPaths.push(path); - } else if (declar.isClass()) { - const name = declar.node.id.name; + } else if (t.isClass(declar)) { + const name = declar.id.name; exportNames.push(name); exportValues.push(scope.buildUndefinedNode()); - variableIds.push(t.cloneNode(declar.node.id)); + variableIds.push(t.cloneNode(declar.id)); path.replaceWith( t.expressionStatement( t.assignmentExpression( "=", - t.cloneNode(declar.node.id), - t.toExpression(declar.node), + t.cloneNode(declar.id), + t.toExpression(declar), ), ), ); addExportName(name, name); } else { - if (declar.isVariableDeclaration()) { + if (t.isVariableDeclaration(declar)) { // Convert top-level variable declarations to "var", // because they must be hoisted - declar.node.kind = "var"; + declar.kind = "var"; } for (const name of Object.keys( - declar.getBindingIdentifiers(), + t.getBindingIdentifiers(declar), )) { addExportName(name, name); } diff --git a/packages/babel-plugin-transform-modules-umd/src/index.ts b/packages/babel-plugin-transform-modules-umd/src/index.ts index 955e23ac9ee4..072987e16db0 100644 --- a/packages/babel-plugin-transform-modules-umd/src/index.ts +++ b/packages/babel-plugin-transform-modules-umd/src/index.ts @@ -3,6 +3,7 @@ import { basename, extname } from "path"; import { isModule, rewriteModuleStatementsAndPrepareHeader, + type RewriteModuleStatementsAndPrepareHeaderOptions, hasExports, isSideEffectImport, buildNamespaceInitStatements, @@ -44,7 +45,7 @@ export interface Options extends PluginOptions { allowTopLevelThis?: boolean; exactGlobals?: boolean; globals?: Record; - importInterop?: "babel" | "node"; + importInterop?: RewriteModuleStatementsAndPrepareHeaderOptions["importInterop"]; loose?: boolean; noInterop?: boolean; strict?: boolean; @@ -73,10 +74,10 @@ export default declare((api, options: Options) => { * Build the assignment statements that initialize the UMD global. */ function buildBrowserInit( - browserGlobals, - exactGlobals, - filename, - moduleName, + browserGlobals: Record, + exactGlobals: boolean, + filename: string, + moduleName: t.StringLiteral | void, ) { const moduleNameOrBasename = moduleName ? moduleName.value @@ -121,17 +122,22 @@ export default declare((api, options: Options) => { /** * Build the member expression that reads from a global for a given source. */ - function buildBrowserArg(browserGlobals, exactGlobals, source) { - let memberExpression; + function buildBrowserArg( + browserGlobals: Record, + exactGlobals: boolean, + source: string, + ) { + let memberExpression: t.MemberExpression; if (exactGlobals) { const globalRef = browserGlobals[source]; if (globalRef) { memberExpression = globalRef .split(".") .reduce( - (accum, curr) => t.memberExpression(accum, t.identifier(curr)), + (accum: t.Identifier | t.MemberExpression, curr) => + t.memberExpression(accum, t.identifier(curr)), t.identifier("global"), - ); + ) as t.MemberExpression; } else { memberExpression = t.memberExpression( t.identifier("global"), @@ -159,9 +165,9 @@ export default declare((api, options: Options) => { const browserGlobals = globals || {}; - let moduleName = getModuleName(this.file.opts, options); - // @ts-expect-error todo(flow->ts): do not reuse variables - if (moduleName) moduleName = t.stringLiteral(moduleName); + const moduleName = getModuleName(this.file.opts, options); + let moduleNameLiteral: void | t.StringLiteral; + if (moduleName) moduleNameLiteral = t.stringLiteral(moduleName); const { meta, headers } = rewriteModuleStatementsAndPrepareHeader( path, @@ -240,7 +246,8 @@ export default declare((api, options: Options) => { path.node.body = []; const umdWrapper = path.pushContainer("body", [ buildWrapper({ - MODULE_NAME: moduleName, + //todo: buildWrapper does not handle void moduleNameLiteral + MODULE_NAME: moduleNameLiteral, AMD_ARGUMENTS: t.arrayExpression(amdArgs), COMMONJS_ARGUMENTS: commonjsArgs, @@ -251,7 +258,7 @@ export default declare((api, options: Options) => { browserGlobals, exactGlobals, this.filename || "unknown", - moduleName, + moduleNameLiteral, ), }) as t.Statement, ])[0] as NodePath; diff --git a/packages/babel-traverse/src/path/family.ts b/packages/babel-traverse/src/path/family.ts index d50bacf908e9..e292e03e9d5a 100644 --- a/packages/babel-traverse/src/path/family.ts +++ b/packages/babel-traverse/src/path/family.ts @@ -11,8 +11,8 @@ import { } from "@babel/types"; import type * as t from "@babel/types"; -const NORMAL_COMPLETION = 0; -const BREAK_COMPLETION = 1; +const NORMAL_COMPLETION = 0 as const; +const BREAK_COMPLETION = 1 as const; type Completion = { path: NodePath; @@ -65,7 +65,7 @@ function completionRecordForSwitch( context: CompletionContext, ): Completion[] { // https://tc39.es/ecma262/#sec-runtime-semantics-caseblockevaluation - let lastNormalCompletions = []; + let lastNormalCompletions: Completion[] = []; for (let i = 0; i < cases.length; i++) { const casePath = cases[i]; const caseCompletions = _getCompletionRecords(casePath, context); @@ -227,7 +227,7 @@ function _getCompletionRecords( path: NodePath, context: CompletionContext, ): Completion[] { - let records = []; + let records: Completion[] = []; if (path.isIfStatement()) { records = addCompletionRecords(path.get("consequent"), records, context); records = addCompletionRecords(path.get("alternate"), records, context); @@ -413,7 +413,9 @@ export function _getKey( context?: TraversalContext, ): NodePath | NodePath[] { const node = this.node; - const container = node[key]; + const container = + // @ts-ignore + node[key]; if (Array.isArray(container)) { // requested a container so give them all the paths @@ -448,6 +450,7 @@ export function _getPattern( path = path.parentPath; } else { if (Array.isArray(path)) { + // @ts-ignore path = path[part]; } else { path = path.get(part, context); @@ -503,7 +506,8 @@ export function getBindingIdentifierPaths( duplicates: boolean = false, outerOnly: boolean = false, ): { - [x: string]: NodePath; + // todo: returns NodePath[] when duplicates is true + [x: string]: NodePath; } { const path = this; const search = [path]; @@ -514,7 +518,9 @@ export function getBindingIdentifierPaths( if (!id) continue; if (!id.node) continue; - const keys = _getBindingIdentifiers.keys[id.node.type]; + const keys = + // @ts-ignore + _getBindingIdentifiers.keys[id.node.type]; if (id.isIdentifier()) { if (duplicates) { @@ -564,8 +570,6 @@ export function getBindingIdentifierPaths( export function getOuterBindingIdentifierPaths( this: NodePath, duplicates?: boolean, -): { - [x: string]: NodePath; -} { +) { return this.getBindingIdentifierPaths(duplicates, true); }