javascript是没有模块的概念的,这意味着,如果你想在其他文件中调用一个函数,你必须记住在调用函数之前通过脚本标签显式地加载该文件。
在其他语言中,想要使用其他文件中的函数时,比如python,只需要
import foo from bar;
foo();
这个特性在JavaScript中是缺失的,所以社区开发了自己的解决方案,比如在node中使用的CommonJS。
ES6 Modules
ES6采用了现有的模块系统,并在语言级别上引入了这个概念。
尽管它已经进入了ES6标准,但要由javascript引擎制造商还没有来实际实现它,所以我们在Typescript中使用,在编译的时候将会根据CommonJs规范进行编译转化
==typescript编译器默认是根据Commonjs来编译的,但是可以配置文件中配置==
导出Exporting
// utils.ts
function square(x) {
return Math.pow(x,2)
}
function cow() {
console.log("Mooooo!!!")
}
export {square, cow};
在上面文件中有两个方法square和cow,可以通过==export==关键字导出方法,然后在其他模块文件中,用==import==关键字引入方法
Importing 导入
// script.ts
import {square, cow} from './utils';
console.log(square(2));
cow();
别名 Aliases
我们再导入的时候,可以自定义一个别称,例如:
import {square as sqr} from './utils';
sqr(2);
或者我们可以一次性导入所有,然后统一名称这样写
import * as utils from './utils';
console.log(utils.square(2));
utils.cow();
export 导出语法
通常都是用export关键字导出
export {square, cow};
其实我们不用预先定义而直接导出函数或者变量,如
export function square(x) {
return Math.pow(x,2)
}
export中default
如果一个文件中,导出一个使用最多的函数或者变量等,就可以使用default关键字
export default function square(x) {
return Math.pow(x,2)
}
这样在导入的时候就不需要{}
import square from './utils';
如果想导出默认的和其他的,就可以这样使用
import square, { cow } from './utils';
总结
有了ES6模块,我们终于有了一种机制,可以让语言处理为我们加载依赖文件。