我正在构建一个共享组件库,React和Vue都将使用它。
我使用的是Styletron,它需要一个特定于框架的适配器,但在其他方面几乎是一样的。
因此,从我的源代码(一堆函数)中,我需要生成一个文件夹,其中的代码可以正常转换,然后生成另一个文件夹,其中的函数稍有修改。
这是我的代码:
const MyComponent = styled('div', ({ isActive, hasBorder}) => ({
color: 'red'
}))
// should not change
const OtherComponent = styled('div', {
background: 'blue'
})它应该变成:
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写的插件:
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
}
}
}
}
};
}发布于 2018-04-07 00:39:02
Babel变换与AST节点一起工作,所以以这种方式将道具串行化并将其推入参数列表将不会很好地工作。您需要从您的对象实际创建一个AST结构。
在这种情况下,Babel为此提供了一个帮助器,因此您可以更改
path.node.arguments.push(JSON.stringify(props))至
path.node.arguments.push(t.valueToNode(props))https://stackoverflow.com/questions/49697181
复制相似问题