有一个选项可以使用babel将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/开放源码(我的代码在左边)
发布于 2016-01-29 13:43:28
打开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演示有选择
发布于 2016-01-28 19:50:27
若要将ES5更改为ES6,可以使用此https://www.npmjs.com/package/xto6
你必须安装它
npm install -g xto6然后只是:
xto6 es5.js -o es6.js也有一元化插件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/'));
});发布于 2016-01-28 19:55:34
你在找ES5到ES6还是ES6到ES5?你的小提琴曲有一个ES6源。
我建议在https://github.com/Daniel15/babel-standalone上查看babel-独立项目。
我修改了你的小提琴曲,用ES2015预置它来转换代码,这就是你想要的:https://jsfiddle.net/bdrg01Lg/。
它就像
var input = 'const getMessage = () => "Hello World";';
var output = Babel.transform(input, { presets: ['es2015'] }).code;https://stackoverflow.com/questions/35017792
复制相似问题