我正在构建一个将由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
}
}
}
}
};
}
答案 0 :(得分:0)
Babel转换使用AST节点,因此以这种方式对道具进行字符串化并将它们推入参数列表将不会正常工作。您将要从对象中实际创建AST结构。
在这种情况下,Babel为此提供帮助,因此您可以更改
path.node.arguments.push(JSON.stringify(props))
到
path.node.arguments.push(t.valueToNode(props))