首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Babel插件错误未定义类型的未知节点,构造函数为"String“

Babel插件错误未定义类型的未知节点,构造函数为"String“
EN

Stack Overflow用户
提问于 2018-04-07 00:24:11
回答 1查看 742关注 0票数 1

我正在构建一个共享组件库,React和Vue都将使用它。

我使用的是Styletron,它需要一个特定于框架的适配器,但在其他方面几乎是一样的。

因此,从我的源代码(一堆函数)中,我需要生成一个文件夹,其中的代码可以正常转换,然后生成另一个文件夹,其中的函数稍有修改。

这是我的代码:

代码语言:javascript
复制
const MyComponent = styled('div', ({ isActive, hasBorder}) => ({
  color: 'red'
}))

// should not change
const OtherComponent = styled('div', {
  background: 'blue'
})

它应该变成:

代码语言:javascript
复制
const MyComponent = styled('div', ({ isActive, hasBorder}) => ({
  color: 'red'
}), ['isActive', 'hasBorder'])

const OtherComponent = styled('div', {
  background: 'blue'
})

实际上,我在ASTExplorer中有一个可以正常工作的示例,但是当我尝试用它制作一个插件时,我遇到了错误Babel plugin error unknown node of type undefined with constructor "String"

这是我的第一个插件,我知道我做错了一些事情,但现在我只需要找出我必须做什么才能在ASTExplorer之外工作。

这是我用ASTExplorer写的插件:

代码语言:javascript
复制
export default function(babel) {
  const { types: t } = babel;
  return {
    name: "ast-transform",
    visitor: {
      CallExpression: (path) => {
        if (
          path.node.callee.name === 'styled' && 
          path.node.arguments.length === 2 && 
          t.isArrowFunctionExpression(path.node.arguments[1])
        ) {
          if (t.isObjectPattern(path.node.arguments[1].params[0])) {
            const props = []
            path.node.arguments[1].params[0].properties.map(prop => props.push(prop.value.name))
            path.node.arguments.push(JSON.stringify(props)) // I suspect that the error is from here
          }
        } 

      }
    }
  };
}
EN

回答 1

Stack Overflow用户

发布于 2018-04-07 00:39:02

Babel变换与AST节点一起工作,所以以这种方式将道具串行化并将其推入参数列表将不会很好地工作。您需要从您的对象实际创建一个AST结构。

在这种情况下,Babel为此提供了一个帮助器,因此您可以更改

代码语言:javascript
复制
path.node.arguments.push(JSON.stringify(props))

代码语言:javascript
复制
path.node.arguments.push(t.valueToNode(props))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49697181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档