Skip to content

Commit

Permalink
Implement plugin-transform-typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
sosukesuzuki committed Sep 30, 2021
1 parent 00feb7b commit cd5791d
Showing 1 changed file with 35 additions and 11 deletions.
46 changes: 35 additions & 11 deletions packages/babel-plugin-transform-typescript/src/index.ts
Expand Up @@ -229,9 +229,23 @@ export default declare((api, opts) => {
continue;
}

const importsToRemove: NodePath<t.Node>[] = [];
const specifiersLength = stmt.node.specifiers.length;
const isAllSpecifiersElided = () =>
specifiersLength > 0 &&
specifiersLength === importsToRemove.length;

// If onlyRemoveTypeImports is `true`, only remove type-only imports
// and exports introduced in TypeScript 3.8.
if (onlyRemoveTypeImports) {
for (const specifier of stmt.node.specifiers) {
if (specifier.importKind === "type") {
const binding = stmt.scope.getBinding(specifier.local.name);
if (binding) {
importsToRemove.push(binding.path);
}
}
}
NEEDS_EXPLICIT_ESM.set(path.node, false);
} else {
// Note: this will allow both `import { } from "m"` and `import "m";`.
Expand All @@ -241,9 +255,6 @@ export default declare((api, opts) => {
continue;
}

let allElided = true;
const importsToRemove: NodePath<t.Node>[] = [];

for (const specifier of stmt.node.specifiers) {
const binding = stmt.scope.getBinding(specifier.local.name);

Expand All @@ -264,17 +275,16 @@ export default declare((api, opts) => {
) {
importsToRemove.push(binding.path);
} else {
allElided = false;
NEEDS_EXPLICIT_ESM.set(path.node, false);
}
}
}

if (allElided) {
stmt.remove();
} else {
for (const importPath of importsToRemove) {
importPath.remove();
}
if (isAllSpecifiersElided()) {
stmt.remove();
} else {
for (const importPath of importsToRemove) {
importPath.remove();
}
}

Expand Down Expand Up @@ -325,6 +335,17 @@ export default declare((api, opts) => {
return;
}

// remove export declaration that is filled with type-only specifiers
// export { type A1, type A2 } from "a";
if (
path.node.source &&
path.node.specifiers.length > 0 &&
path.node.specifiers.every(({ exportKind }) => exportKind === "type")
) {
path.remove();
return;
}

// remove export declaration if it's exporting only types
// This logic is needed when exportKind is "value", because
// currently the "type" keyword is optional.
Expand All @@ -348,7 +369,10 @@ export default declare((api, opts) => {

ExportSpecifier(path) {
// remove type exports
if (!path.parent.source && isGlobalType(path, path.node.local.name)) {
if (
(!path.parent.source && isGlobalType(path, path.node.local.name)) ||
path.node.exportKind === "type"
) {
path.remove();
}
},
Expand Down

0 comments on commit cd5791d

Please sign in to comment.