Skip to content

Commit

Permalink
improve helper-module-imports typings (#14623)
Browse files Browse the repository at this point in the history
* refactor: simplify ImportInjector._applyDefaults

* helper-module-imports

* map globals to the one used in Babel 8
  • Loading branch information
JLHwung committed Jun 21, 2022
1 parent 2ea5c45 commit a32418b
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 58 deletions.
45 changes: 24 additions & 21 deletions packages/babel-helper-module-imports/src/import-builder.ts
Expand Up @@ -13,20 +13,23 @@ import {
variableDeclaration,
variableDeclarator,
} from "@babel/types";
import type * as t from "@babel/types";
import type { Scope } from "@babel/traverse";
import type { File } from "@babel/core";

/**
* A class to track and accumulate mutations to the AST that will eventually
* output a new require/import statement list.
*/
export default class ImportBuilder {
_statements = [];
_resultName = null;
private _statements: t.Statement[] = [];
private _resultName: t.Identifier | t.MemberExpression = null;

_scope = null;
_hub = null;
private _importedSource: any;
declare _scope: Scope;
declare _hub: File["hub"];
private _importedSource: string;

constructor(importedSource, scope, hub) {
constructor(importedSource: string, scope: Scope, hub: File["hub"]) {
this._scope = scope;
this._hub = hub;
this._importedSource = importedSource;
Expand Down Expand Up @@ -67,39 +70,39 @@ export default class ImportBuilder {
this._resultName = cloneNode(local);
return this;
}
default(name) {
name = this._scope.generateUidIdentifier(name);
default(name: string) {
const id = this._scope.generateUidIdentifier(name);
const statement = this._statements[this._statements.length - 1];
assert(statement.type === "ImportDeclaration");
assert(statement.specifiers.length === 0);
statement.specifiers = [importDefaultSpecifier(name)];
this._resultName = cloneNode(name);
statement.specifiers = [importDefaultSpecifier(id)];
this._resultName = cloneNode(id);
return this;
}
named(name, importName) {
named(name: string, importName: string) {
if (importName === "default") return this.default(name);

name = this._scope.generateUidIdentifier(name);
const id = this._scope.generateUidIdentifier(name);
const statement = this._statements[this._statements.length - 1];
assert(statement.type === "ImportDeclaration");
assert(statement.specifiers.length === 0);
statement.specifiers = [importSpecifier(name, identifier(importName))];
this._resultName = cloneNode(name);
statement.specifiers = [importSpecifier(id, identifier(importName))];
this._resultName = cloneNode(id);
return this;
}

var(name) {
name = this._scope.generateUidIdentifier(name);
var(name: string) {
const id = this._scope.generateUidIdentifier(name);
let statement = this._statements[this._statements.length - 1];
if (statement.type !== "ExpressionStatement") {
assert(this._resultName);
statement = expressionStatement(this._resultName);
this._statements.push(statement);
}
this._statements[this._statements.length - 1] = variableDeclaration("var", [
variableDeclarator(name, statement.expression),
variableDeclarator(id, statement.expression),
]);
this._resultName = cloneNode(name);
this._resultName = cloneNode(id);
return this;
}

Expand All @@ -110,7 +113,7 @@ export default class ImportBuilder {
return this._interop(this._hub.addHelper("interopRequireWildcard"));
}

_interop(callee) {
_interop(callee: t.Expression) {
const statement = this._statements[this._statements.length - 1];
if (statement.type === "ExpressionStatement") {
statement.expression = callExpression(callee, [statement.expression]);
Expand All @@ -125,7 +128,7 @@ export default class ImportBuilder {
return this;
}

prop(name) {
prop(name: string) {
const statement = this._statements[this._statements.length - 1];
if (statement.type === "ExpressionStatement") {
statement.expression = memberExpression(
Expand All @@ -144,7 +147,7 @@ export default class ImportBuilder {
return this;
}

read(name) {
read(name: string) {
this._resultName = memberExpression(this._resultName, identifier(name));
}
}
73 changes: 41 additions & 32 deletions packages/babel-helper-module-imports/src/import-injector.ts
@@ -1,7 +1,8 @@
import assert from "assert";
import { numericLiteral, sequenceExpression } from "@babel/types";
import type * as t from "@babel/types";
import type { NodePath, Scope, HubInterface } from "@babel/traverse";
import type { NodePath, Scope } from "@babel/traverse";
import type { File } from "@babel/core";

import ImportBuilder from "./import-builder";
import isModule from "./is-module";
Expand Down Expand Up @@ -93,8 +94,8 @@ export type ImportOptions = {
*/
importPosition: "before" | "after";

nameHint?;
blockHoist?;
nameHint?: string;
blockHoist?: number;
};

/**
Expand All @@ -114,7 +115,7 @@ export default class ImportInjector {
/**
* The file used to inject helpers and resolve paths.
*/
declare _hub: HubInterface;
declare _hub: File["hub"];

/**
* The default options to use with this instance when imports are added.
Expand All @@ -129,21 +130,29 @@ export default class ImportInjector {
importPosition: "before",
};

constructor(path: NodePath, importedSource?, opts?) {
constructor(
path: NodePath,
importedSource?: string,
opts?: Partial<ImportOptions>,
) {
const programPath = path.find(p => p.isProgram()) as NodePath<t.Program>;

this._programPath = programPath;
this._programScope = programPath.scope;
this._hub = programPath.hub;
this._hub = programPath.hub as File["hub"];

this._defaultOpts = this._applyDefaults(importedSource, opts, true);
}

addDefault(importedSourceIn, opts) {
addDefault(importedSourceIn: string, opts: Partial<ImportOptions>) {
return this.addNamed("default", importedSourceIn, opts);
}

addNamed(importName, importedSourceIn, opts) {
addNamed(
importName: string,
importedSourceIn: string,
opts: Partial<ImportOptions>,
) {
assert(typeof importName === "string");

return this._generateImport(
Expand All @@ -152,49 +161,44 @@ export default class ImportInjector {
);
}

addNamespace(importedSourceIn, opts) {
addNamespace(importedSourceIn: string, opts: Partial<ImportOptions>) {
return this._generateImport(
this._applyDefaults(importedSourceIn, opts),
null,
);
}

addSideEffect(importedSourceIn, opts) {
addSideEffect(importedSourceIn: string, opts: Partial<ImportOptions>) {
return this._generateImport(
this._applyDefaults(importedSourceIn, opts),
false,
void 0,
);
}

_applyDefaults(importedSource, opts, isInit = false) {
const optsList = [];
_applyDefaults(
importedSource: string | Partial<ImportOptions>,
opts: Partial<ImportOptions> | undefined,
isInit = false,
) {
let newOpts: ImportOptions;
if (typeof importedSource === "string") {
optsList.push({ importedSource });
optsList.push(opts);
newOpts = { ...this._defaultOpts, importedSource, ...opts };
} else {
assert(!opts, "Unexpected secondary arguments.");

optsList.push(importedSource);
newOpts = { ...this._defaultOpts, ...importedSource };
}

const newOpts: ImportOptions = {
...this._defaultOpts,
};
for (const opts of optsList) {
if (!opts) continue;
Object.keys(newOpts).forEach(key => {
if (opts[key] !== undefined) newOpts[key] = opts[key];
});

if (!isInit) {
if (opts.nameHint !== undefined) newOpts.nameHint = opts.nameHint;
if (opts.blockHoist !== undefined) newOpts.blockHoist = opts.blockHoist;
}
if (!isInit && opts) {
if (opts.nameHint !== undefined) newOpts.nameHint = opts.nameHint;
if (opts.blockHoist !== undefined) newOpts.blockHoist = opts.blockHoist;
}
return newOpts;
}

_generateImport(opts, importName) {
_generateImport(
opts: Partial<ImportOptions>,
importName: string | null | undefined,
) {
const isDefault = importName === "default";
const isNamed = !!importName && !isDefault;
const isNamespace = importName === null;
Expand Down Expand Up @@ -422,7 +426,11 @@ export default class ImportInjector {
return resultName;
}

_insertStatements(statements, importPosition = "before", blockHoist = 3) {
_insertStatements(
statements: t.Statement[],
importPosition = "before",
blockHoist = 3,
) {
const body = this._programPath.get("body");

if (importPosition === "after") {
Expand All @@ -434,6 +442,7 @@ export default class ImportInjector {
}
} else {
statements.forEach(node => {
// @ts-expect-error handle _blockHoist
node._blockHoist = blockHoist;
});

Expand Down
66 changes: 61 additions & 5 deletions packages/babel-helper-module-imports/src/index.ts
@@ -1,21 +1,77 @@
import ImportInjector from "./import-injector";
import ImportInjector, { type ImportOptions } from "./import-injector";
import type { NodePath } from "@babel/traverse";
import type * as t from "@babel/types";

export { ImportInjector };

export { default as isModule } from "./is-module";

export function addDefault(path, importedSource, opts?) {
export function addDefault(
path: NodePath,
importedSource: string,
opts?: Partial<ImportOptions>,
) {
return new ImportInjector(path).addDefault(importedSource, opts);
}

export function addNamed(path, name, importedSource, opts?) {
function addNamed(
path: NodePath,
name: string,
importedSource: string,
opts?: Omit<
Partial<ImportOptions>,
"ensureLiveReference" | "ensureNoContext"
>,
): t.Identifier;
function addNamed(
path: NodePath,
name: string,
importedSource: string,
opts?: Omit<Partial<ImportOptions>, "ensureLiveReference"> & {
ensureLiveReference: true;
},
): t.MemberExpression;
function addNamed(
path: NodePath,
name: string,
importedSource: string,
opts?: Omit<Partial<ImportOptions>, "ensureNoContext"> & {
ensureNoContext: true;
},
): t.SequenceExpression;
/**
* add a named import to the program path of given path
*
* @export
* @param {NodePath} path The starting path to find a program path
* @param {string} name The name of the generated binding. Babel will prefix it with `_`
* @param {string} importedSource The source of the import
* @param {Partial<ImportOptions>} [opts]
* @returns {t.Identifier | t.MemberExpression | t.SequenceExpression} If opts.ensureNoContext is true, returns a SequenceExpression,
* else if opts.ensureLiveReference is true, returns a MemberExpression, else returns an Identifier
*/
function addNamed(
path: NodePath,
name: string,
importedSource: string,
opts?: Partial<ImportOptions>,
) {
return new ImportInjector(path).addNamed(name, importedSource, opts);
}
export { addNamed };

export function addNamespace(path, importedSource, opts?) {
export function addNamespace(
path: NodePath,
importedSource: string,
opts?: Partial<ImportOptions>,
) {
return new ImportInjector(path).addNamespace(importedSource, opts);
}

export function addSideEffect(path, importedSource, opts?) {
export function addSideEffect(
path: NodePath,
importedSource: string,
opts?: Partial<ImportOptions>,
) {
return new ImportInjector(path).addSideEffect(importedSource, opts);
}
1 change: 1 addition & 0 deletions scripts/generators/tsconfig.js
Expand Up @@ -116,6 +116,7 @@ fs.writeFileSync(
"babel-plugin-dynamic-import-node/utils",
["./lib/babel-plugin-dynamic-import-node.d.ts"],
],
["globals", ["./node_modules/globals-BABEL_8_BREAKING-true"]],
]),
},
},
Expand Down
3 changes: 3 additions & 0 deletions tsconfig.json
Expand Up @@ -698,6 +698,9 @@
],
"babel-plugin-dynamic-import-node/utils": [
"./lib/babel-plugin-dynamic-import-node.d.ts"
],
"globals": [
"./node_modules/globals-BABEL_8_BREAKING-true"
]
}
}
Expand Down

0 comments on commit a32418b

Please sign in to comment.