fix transform-flow-comments for import types (#9901)

* fix transform-flow-comments for import types

* update: dependencies
This commit is contained in:
Tan Li Hau
2019-07-13 22:06:42 +08:00
committed by Nicolò Ribaudo
parent f5ca0587d1
commit 8b9af1be2f
4 changed files with 52 additions and 4 deletions

View File

@@ -1,21 +1,26 @@
import { declare } from "@babel/helper-plugin-utils";
import syntaxFlow from "@babel/plugin-syntax-flow";
import { types as t } from "@babel/core";
import generateCode from "@babel/generator";
export default declare(api => {
api.assertVersion(7);
function wrapInFlowComment(path, parent) {
function attachComment(path, comment) {
let attach = path.getPrevSibling();
let where = "trailing";
if (!attach.node) {
attach = path.parentPath;
where = "inner";
}
attach.addComment(where, generateComment(path, parent));
attach.addComment(where, comment);
path.remove();
}
function wrapInFlowComment(path, parent) {
attachComment(path, generateComment(path, parent));
}
function generateComment(path, parent) {
let comment = path
.getSource()
@@ -26,6 +31,10 @@ export default declare(api => {
return comment;
}
function isTypeImport(importKind) {
return importKind === "type" || importKind === "typeof";
}
return {
name: "transform-flow-comments",
inherits: syntaxFlow,
@@ -122,10 +131,33 @@ export default declare(api => {
// support `import type A` and `import typeof A` #10
ImportDeclaration(path) {
const { node, parent } = path;
if (node.importKind !== "type" && node.importKind !== "typeof") {
if (isTypeImport(node.importKind)) {
wrapInFlowComment(path, parent);
return;
}
wrapInFlowComment(path, parent);
const typeSpecifiers = node.specifiers.filter(specifier =>
isTypeImport(specifier.importKind),
);
const nonTypeSpecifiers = node.specifiers.filter(
specifier => !isTypeImport(specifier.importKind),
);
node.specifiers = nonTypeSpecifiers;
if (typeSpecifiers.length > 0) {
const typeImportNode = t.cloneNode(node);
typeImportNode.specifiers = typeSpecifiers;
if (nonTypeSpecifiers.length > 0) {
path.addComment(
"trailing",
`:: ${generateCode(typeImportNode).code}`,
);
} else {
attachComment(path, `:: ${generateCode(typeImportNode).code}`);
}
}
},
ObjectPattern(path) {
const { node } = path;