[英]Extending Javascript with new syntax
Im working on a project in which i'm trying to simplify the syntax of an older package, ie:我正在从事一个项目,我试图在其中简化旧版 package 的语法,即:
I want to convert something like我想转换类似的东西
digitalPulse(LED2,1,1000)
to puck.LED.flash("red",1000)
digitalPulse(LED2,1,1000)
to puck.LED.flash("red",1000)
Where LED2 is a red LED always.其中 LED2 始终是红色 LED。 There are around 50 of these examples.
这些例子大约有 50 个。
After investigating this online everything is pointing to building a transpiler/preprocessor.在网上调查之后,一切都指向构建一个转译器/预处理器。 Is this the best method as these blocks of code will be used within files, an example of their usage could be.
这是最好的方法吗,因为这些代码块将在文件中使用,它们的用法示例可能是。
let puck = new Puck();
if(...){
puck.LED.flash("green",1000);
else {
puck.LED.flash("red",1000);
}
This particular example would be converted to这个特定的例子将被转换为
if(...){
digitalPulse(LED1,1,1000)}
} else {
digitalPulse(LED2,1,1000)}
}
In addition to this there are also除此之外还有
setWatch(function(){
LED2.set();
}, BTN,{edge:"rising", repeat:true, debounce:50})
which should translate to below, which accepts other parsed code in the function such as below: Some functions such as onPress assume default values like in this case there is no need to specify BTN or the object containing edge, repeat and debounce这应该翻译成下面,它接受 function 中的其他解析代码,如下所示:一些函数,如 onPress 假设默认值,在这种情况下,不需要指定 BTN 或 object 包含边缘,重复和去抖动
puck.onPress(function(){
puck.LED.on("red");
}
How can I approach this without overcomplicating it as ive already fallen down a rabbit hole of transpilers/preprocessors trying my own tokenization, parsing to generate an AST and transpiling, but ive not been successful and havent been able to find an example of this online to see exactly.我怎样才能在不使它过于复杂的情况下解决这个问题,因为我已经掉进了转译器/预处理器的兔子洞,尝试我自己的标记化、解析以生成 AST 和转译,但我没有成功,也无法在网上找到这个例子看清楚了。
Is there a better approach to this problem can anybody recommend tools to assist with this or with direction of where I should be researching.有没有更好的方法来解决这个问题,任何人都可以推荐工具来帮助解决这个问题或指导我应该研究的方向。
My understanding is that you want to migrate a legacy procedural code to modern object oriented Javascript.我的理解是,您想将遗留程序代码迁移到面向现代 object 的 Javascript。
The 1st thing is to understand what is the target:第一件事是了解目标是什么:
const div = document.querySelector("div"); class Led { constructor() { } flash(color, time) { div.style.backgroundColor = color; setTimeout(() => div.style.backgroundColor = "", time); } } class Puck { constructor() { this.LED = new Led(); } } const puck = new Puck(); if(Math.random() > 0.5){ puck.LED.flash("green", 1000); } else { puck.LED.flash("red", 1000); }
<div style="width: 100px; height: 100px">LED</div>
If you really need to target old browser versions, I suggest to use Babel as a transpiler.如果你真的需要针对旧浏览器版本,我建议使用Babel作为转译器。
Feel free to give more detail so I can give you a more appropriate answer.请随时提供更多详细信息,以便我给您更合适的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.