之前在工作中需要将一个ES5编写的开源项目使用到ES6的项目中,为了使代码风格、写法保持一致,找到了lebab.js,它与babel.js的作用相反,是将ES5编写的代码转换成ES6或ES7编写的代码。它支持单文件转换和整个目录转换,并且可以指定转换的类型(arrow、class、let,etc)。

1、安装lebab

使用npm安装lebab: npm install -g lebab

2、使用

  • 单个文件转换

lebab es5.js -o es6.js --transform let,class

  • 整个目录转换

lebab --replace src/js/ --transform class,let,arrow

3、样例

  • 转换前代码:
var Employee = function Employee(){
	this.alive = true;
};
Employee.prototype.setSkills = function(skills){
	skills = skills || [];
	var defaultSkills = ['JavaScript'];
	this.skills = skills.concat(defaultSkills);
};
Employee.prototpye.sayHello = function(){
	window.setTimeout(function(){
		console.log('Hello World!');
	}, 2000);
};
Object.defineProperty(Employee.prototype, 'name', {
	get: function(){
		return this.firstName + " " + this.lastName;
	}
});
  • 转换命令:

lebab Employee-es5.js -o Employee-es6.js -t class,let,arrow

  • 转换后代码:
class Employee {
    constructor() {
        this.alive = true;
    }

    setSkills(skills) {
        skills = skills || [];
        const defaultSkills = ['JavaScript'];
        this.skills = skills.concat(defaultSkills);
    }

    get name() {
	return this.firstName + " " + this.lastName;
    }
}

Employee.prototpye.sayHello = () => {
	window.setTimeout(() => {
		console.log('Hello World!');
	}, 2000);
};
附:

Lebab GitHub地址:https://github.com/lebab/lebab