导出
//导出变量
let a=1;
export a
//导出函数
export function (){}
//导出对象
export {
a
}
导入
//批量导入
import {a,b} from "./a.ts"
//给导入的变量起一个别名
import {f as F} from "./a.ts"
导出
module.exports.a=4
module.exports={
a
}
导入
require("./a.ts")
commonjs只能引入js文件,如果要引入ts文件,需要将ts文件编译成js文件。
命名空间能有效的避免全局污染,在模块化的背景下,不必担心全局污染,但是在出现全局污染的情况加命名空间是一个有效的解决方案
//使用namespace声明命名空间
namespace Share{
export function square(){
return "hello";
}
}
//调用命名空间中的变量
Share.square()
//引用不同命名空间的变量和函数
///reference path="./a.ts"
命名空间和模块不能混用,不能在模块中使用命名空间,命名空间最好在全局环境中使用。
编译器把程序中相同的声明合并成一个声明
interface A{
x:number
}
interface A{
y:number
}
//声明合并
let a:A={
x:1,
y:1
}
命名空间中导出的成员不可以重复定义,同一个命名空间中不能出现两次同名的变量。
类库分为: 全局类库,模块化类库,UMD类库
有些类库有安装文件,有些类 库没有声明文件。
以jQuery为例,jQuer有声明文件可以直接安装
npm install @types/jQuery
在typeSearch网站查询,输入要查询的类库名称即可
源代码
function globalLib(options){
console.log(options)
}
globalLib.version="1.0.0"
globalLib.doSomething=function (){
console.log("globalLib do something")
}
声明文件
declare function globalLib(options:globalLib.Options):void{
declare namespace globalLib{
const version = "1.0.0"
function doSomething():void
interface Options{
[key:string]:any
}
}
}
const version ="1.0.0"
function doSomething(){
console.log("moduleLib do something")
}
function mobuleLib(options){
console.log(options)
}
moduleLib.version=version
moduleLib.doSomething=doSomething
module.exports=modulesLib
声明文件
declare function moduleLib(options:Options){
interface Options{
[key:string]:any
}
declare namespace moduleLib{
const version :string
function doSomething():void
}
}
export = mobuleLib
(function (root,factory){
if(typeof define === "function" && define.amd){
define(factory)
}else if(typeof module === "object" && module.exports){
module.exports = factory();
}else{
root.umdLib = factory()
}
})(this,function (){
return {
versionL:"1.0.0",
doSomething(){
console.log("umdLib do something");
}
}
})
声明文件
declare namespace umdLib{
const version:string
function doSomething():void
}
export as namespace umdLib
export = umdLib
files:array编辑器需要编译的单个文件的列表
include:array编译器需要编译的文件或目录
exclude:array编辑器需要排除的文件或文件夹
配置可以继承
{
"extends":"./tsconfig.base",
"compileOnSave":true //让编译器在保存文件的时候编译
}
outFile:将相互依赖的文件编译成一个文件,通常用于生成AMD模块
{
"outFile":"./app.js"
}
libTS需要引入的声明文件
{
"lib":["es5"]
}
outDIr:指定输出目录
{
"outDir":"./out"
}
root:指定输入目录
"root":"./src"
declaration:生成声明文件
{
"declaration":true
}