-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
babel相关资料 #95
Comments
语法插件🤔用babbel创造自定义JS语法 |
辅助插件开发
|
NodePath和Node的关联✅副作用处理修改了NodePath中对应的Node, 修改完成之后需要手动映射到NodePath变量中,
作用域处理如果修改了scope,也需要使用相关的path.scope来进行更新作用域信息
|
babel-macros
示例import evalm from 'eval.macro'
const x = evalm`
function fib(n) {
const SQRT_FIVE = Math.sqrt(5);
return Math.round(1/SQRT_FIVE * (Math.pow(0.5 + SQRT_FIVE/2, n) - Math.pow(0.5 - SQRT_FIVE/2, n)));
}
fib(20)
`
// ↓ ↓ ↓ ↓ ↓ ↓
const x = 6765
使用Macro相比Plugin带来的好处
|
节点静态求值export function getJsxValue(path: NodePath<babelTypes.JSXAttribute>) {
// generate
// 单纯字符串
if (babelTypes.isStringLiteral(path.node.value)) {
return path.node.value.value;
}
// {} 这种类型
if (babelTypes.isJSXExpressionContainer(path.node.value)) {
const JSXExpressionContainerExpressionNode = path.node.value.expression;
if (
babelTypes.isStringLiteral(JSXExpressionContainerExpressionNode) ||
babelTypes.isBooleanLiteral(JSXExpressionContainerExpressionNode) ||
babelTypes.isNumericLiteral(JSXExpressionContainerExpressionNode)
) {
return JSXExpressionContainerExpressionNode.value;
}
if (babelTypes.isObjectExpression(JSXExpressionContainerExpressionNode)) {
const result = generate(JSXExpressionContainerExpressionNode);
return eval(`(${result.code})`);
}
}
if (path.node.value === null) {
return true;
}
throw path.buildCodeFrameError("不能赋值为非基本类型");
} 通过内置api可以进行求值 t.evaluate(parse("5 + 5")) // { confident: true, value: 10 }
t.evaluate(parse("!true")) // { confident: true, value: false }
// ❌两个变量相加无法求值,因为变量值在运行时才存在,这里confident为false:
t.evaluate(parse("foo + foo")) // { confident: false, value: undefined } |
...
The text was updated successfully, but these errors were encountered: