Skip to content

Instantly share code, notes, and snippets.

@1uokun
Created April 21, 2019 07:32
Show Gist options
  • Save 1uokun/194051af765a5e4f5c24b9a97e30e2d2 to your computer and use it in GitHub Desktop.
Save 1uokun/194051af765a5e4f5c24b9a97e30e2d2 to your computer and use it in GitHub Desktop.
Implementing JSX with AST
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// 调用svgCompile编译器
var code = 'div h1 {{title}} p {{paragraph}}';
//第一步:词法分析lexical
// 'div h1 {{title}} p {{paragraph}}' to [{type:'',value:''}]
function lexical(code){
return code.split(/\s+/).map((a,i)=>{
if(a.indexOf('{{')===0){
let _value = undefined;
a.replace(/{{(.*?)}}/g,(match, key) => _value=key);
return {type:'text', value:_value}
}else {
return {type:'element',value:a}
}
})
}
console.log(lexical(code))
//第二步:语法分析parse
function parse(tokens){
var AST = {
type: 'Drawing',
body: []
};
//循环依次去除第一个元素,然后删除第一个元素
while(tokens.length > 0){
var currentItem = tokens.shift();
//判断类型,如果是element的话,我们就分析它的语法
if(currentItem.type = 'element'){
}
}
}
String.prototype.render = function (context) {
return this.replace(/{{(.*?)}}/g, (match, key) => context[key.trim()]);
};
//https://github.com/facebook/jsx/blob/master/AST.md
//https://www.cnblogs.com/tugenhua0707/p/7759414.html
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment