简体   繁体   English

当代码为字符串时,重新编译Javascript ES6至ES5代码

[英]Recompiling Javascript ES6 to ES5 code when the code is a string

I tried using facebook's Regenerator to convert ES6 code to ES5 code. 我尝试使用Facebook的Regenerator将ES6代码转换为ES5代码。 The code I need to convert is produced by React-ace editor and it is a string. 我需要转换的代码是由React-ace编辑器生成的,它是一个字符串。 Regenerator does not recognize strings and simply returns them as it was. Regenerator不能识别字符串,而只是按原样返回它们。

I tried using eval() and new Function(), both of which will be executed when passed into regenerator.compile("whatever code I need to compile").code, and the value returned will just be the return value of the executed code. 我尝试使用eval()和new Function(),它们都将在传递到regenerator.compile(“我需要编译的任何代码”).code中时执行,返回的值将只是已执行的返回值码。

Is there a way to convert the string produced by React-ace(or any browser text editor) and converted it to ES5 code? 有没有一种方法可以将React-ace(或任何浏览器文本编辑器)生成的字符串转换为ES5代码? Are there any other libraries that allows you to convert ES6 syntax to ES5? 还有其他库可让您将ES6语法转换为ES5吗?

Working Example with local function declaration: 带有局部函数声明的工作示例:

let testFunction = (b) => {

  let a = (c) => {
    return c
  }

  return b;
}

let regenCode = require('regenerator').compile(testFunction).code;
console.log(regenCode);

this will produce: 这将产生:

function testFunction(b) {

   var a = function (c) {
     return c;
   } 

   return b;
}

Trying to do: 尝试做:

let regenCode = require('regenerator').compile("let testFunction = (b) => { let a = (c) => { return c } return b; }");

but this will simply give the string back to me 但这只会把琴弦还给我

You can only use Regenerator programmatically with an AST , not with a string. 您只能通过AST编程地使用Regenerator,而不能使用字符串。

From the Regenerator documentation : 再生器文档中

AST transformation: AST转换:

 var recast = require("recast"); var ast = recast.parse(es6Source); ast = require("regenerator").transform(ast); var es5Source = recast.print(ast); 

In your case, you'd have to do something like: 对于您的情况,您必须执行以下操作:

var recast = require("recast");
var ast = recast.parse("let testFunction = (b) => { let a = (c) => { return c }; return b; }");
ast = require("regenerator").transform(ast);
var es5Source = recast.print(ast);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM