首页 > 解决方案 > 就像我们在 babelTypes 中一样,将 JavaScript 代码转换为 AST 表示

问题描述

每次想修改都得写t.importDeclaration([t.importDefaultSpecifier(t.identifier(`${importcomponentName}`))], t.stringLiteral(`../components/${importcomponentName}`))

它仅用于导入语句。例如。,如果我想生成一个完整的组件,我必须编写一个冗长的代码,在一个文件中太长并且耗时。我们有什么捷径可以通过一些递归或库或任何工具来做到这一点吗?

标签: javascriptreactjstypescriptbabeljsabstract-syntax-tree

解决方案


Babel 提供@babel/template了这种类型的东西,所以你可以替换

const decl = t.importDeclaration(
  [t.importDefaultSpecifier(t.identifier(`${importcomponentName}`))], 
  t.stringLiteral(`../components/${importcomponentName}`)
);

const decl = template.ast`
  import ${importcomponentName} from "${`../components/${importcomponentName}`}";
`;

推荐阅读