Kua*_*uan 1 typescript ecmascript-6
所有:
我对ES6和TypeScript都很陌生,但我现在正在学习和比较它们.
首先让我困惑的是,有很多相似性重叠,例如,在命名空间和模块方面(如import/from/export等):
我想知道是否有人可以给我一个关于它们用法的简短比较总结.
我也想知道Typescript和ES6之间是否存在关系?
谢谢
这个问题可能更适合StackExchange 的Programmers部分,但是我们开始了.
Typescript中有两种类型的模块,内部模块(名称空间)和外部模块.后者的语法等同于ES6模块语法.
也称为命名空间.在模块沿项目编译时使用内部模块,主要是分离问题的工具,类似于在C#中使用命名空间.使用TypeScript编译器编译时,内部模块将被置于闭包中(通过自调用函数).
MyApp.ts
namespace MyApp {
export class MyClass { }
}
Run Code Online (Sandbox Code Playgroud)
...当编译成ES5时,变成以下憎恶:
MyApp.js
// ES5 compatible
var MyApp;
(function (MyApp) {
var MyClass = (function () {
function MyClass() { }
return MyClass;
})();
MyApp.MyClass = MyClass;
})(MyApp || (MyApp = {}));
Run Code Online (Sandbox Code Playgroud)
当编译成ES6时,变得更清晰,因为类有本机语法:
MyApp.js
// ES6 compatible
var MyApp;
(function (MyApp) {
class MyClass { }
MyApp.MyClass = MyClass;
})(MyApp || (MyApp = {}));
Run Code Online (Sandbox Code Playgroud)
将整个代码库编译为单个输出文件时,内部模块特别有用.
外部模块被单独编译(每个文件),并且被与一个模块加载系统加载(如在ES5,或在本地ES6 RequireJS)在运行时间期间.没有顶级模块声明,因为顶级导出或导入语句本身将指示编译器文件本身是模块,并且应该相应地进行编译.
使用TypeScript编译器编译时,外部模块将包装到选定的模块语法中.目前支持ES5平台上的AMD,CommonJS,UMD,System以及ES6平台上的本机语法.
MyApp.ts
export class MyClass { }
Run Code Online (Sandbox Code Playgroud)
...当编译成ES5时 - 比方说,UMD - 成为以下亵渎:
MyApp.js
// ES5 compatible
(function (deps, factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
} else if (typeof define === 'function' && define.amd) {
define(deps, factory);
}
})(["require", "exports"], function (require, exports) {
var MyClass = (function () {
function MyClass() { }
return MyClass;
})();
exports.MyClass = MyClass;
});
Run Code Online (Sandbox Code Playgroud)
但是,当编译到ES6中时,生成的代码变得无限清晰,因为TypeScript模块语法基于(相当于)ES6模块语法:
MyApp.js
// ES6 compatible
export class MyClass { }
Run Code Online (Sandbox Code Playgroud)
但是,ES6平台尚未得到广泛支持,因此我建议使用ES5编译.这需要额外生成的样板代码的费用,但除了略微增加的带宽之外没有额外的副作用:相同的代码库可以编译到ES5和ES6中,具有功能相同的结果.
| 归档时间: |
|
| 查看次数: |
555 次 |
| 最近记录: |