[英]Transform ES5 code to ES6 at runtime
是否可以选择使用 babel API 将 javascript 代码从 ecma 脚本 5 转换为 ecma 脚本 6? 我的意思是说我使用以下 cdn
https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.js
并使用简单的 ES5 代码提供像数组或对象这样的源,并将其转换为 ES6 代码的某些数组/对象/字符串?
是否有可能用 babel 或其他工具以某种方式实现这一目标?
我的意思是使用这里的一些例子.. https://github.com/addyosmani/es6-equivalents-in-es5
如果我输入源 ES5 代码
[1, 2, 3].map(function(n) { return n * 2; }, this);
在 ES6 中转换为箭头函数
[1, 2, 3].map(n => n * 2);
更新
我需要的实际上是取 ES5 代码并将其更改为 ES6 代码,它可以通过 api
例如,我需要做这样的事情的 API/开源(我的代码在左侧)
打开bin/file.js 。 阅读所有行以了解该脚本。
有趣的部分如下:
var transformer = new Transformer({transformers: transformers});
transformer.readFile(file[0]);
transformer.applyTransformations();
transformer.writeFile(program.outFile);
更具体地说, transformer.applyTransformations();
让我们打开/src/transformer.js
在这个文件中,我看到了一些有用的功能:
/**
* Prepare an abstract syntax tree for given code in string
*
* @param string
*/
read(string) {
this.ast = astGenerator.read(string, this.options);
}
所以你可以使用带有一串代码(不是文件)的转换器
现在您可以应用转换“ES5 到 ES6”
/**
* Apply All transformations
*/
applyTransformations() {
for (let i = 0; i < this.transformations.length; i++) {
let transformation = this.transformations[i];
this.applyTransformation(transformation);
}
然后,将其重新转换为字符串
out() {
let result = recast.print(this.ast).code;
if(this.options.formatter) {
result = formatter.format(result, this.options.formatter);
}
return result;
}
var transformer = new Transformer({});
transformer.read('var mySourceCode = "in ES5"');
transformer.applyTransformations();
console.log(transformer.out());
JSFiddle演示在这里
如果您不想要所有转换,您可以使用选项选择您想要的:
var transformers = {
classes: false,
stringTemplates: false,
arrowFunctions: true,
let: false,
defaultArguments: false,
objectMethods: false,
objectShorthands: false,
noStrict: false,
importCommonjs: false,
exportCommonjs: false,
};
var transformer = new Transformer({transformers: transformers});
带有选项的JSFiddle 演示
要将 ES5 更改为 ES6,您可以使用此https://www.npmjs.com/package/xto6
你必须安装它
npm install -g xto6
然后只是:
xto6 es5.js -o es6.js
还有 gulp 插件https://www.npmjs.com/package/gulp-xto6 :
var gulp = require('gulp');
var xto6 = require('gulp-xto6');
gulp.task('default', function () {
return gulp.src('path/to/fixtures/es5/*.js')
.pipe(xto6())
.pipe(gulp.dest('path/to/fixtures/es6/'));
});
您是在寻找 ES5 到 ES6 还是 ES6 到 ES5? 你的 jsfiddle 有一个 ES6 源代码。
我建议查看https://github.com/Daniel15/babel-standalone上的 babel-standalone 项目
我修改了你的 jsfiddle 以使用 ES2015 预设转换代码,这就是你要找的: https ://jsfiddle.net/bdrg01Lg/
就这么简单
var input = 'const getMessage = () => "Hello World";';
var output = Babel.transform(input, { presets: ['es2015'] }).code;
对于只想在线将ES5
代码转换为ES6
。 使用Lebab 现场演示,只需粘贴您的代码,它将被转换为ES6
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.