ts模块

123 阅读2分钟

ts的模块系统是其组织和管理代码的核心机制,它允许你将代码分割成独立的、可复用的单元,并控制其作用域和依赖关系。这极大地提升了大型项目的可维护性和可扩展性。

1.在ts中,任何包含顶级import或export声明的文件都被视为一个模块。相反没有这些生命的文件会视为全局脚本上下文,其内容对所有其他文件可见。

2.导出(Export)

使用export关键字可以将变量、函数、类、接口或类型别名暴露给其他模块。

image.png

//myModule.ts文件
export function sum(a:number,b:number):number{
    return a+b
}
export const name="ly"
import { name, sum } from "@/untils/mathUtils.ts";
console.log("----------------", sum(6, 6));
console.log("----------------", name);

image.png

3.引入,导入(import)

// main.ts
import subtract, { PI, add, Calculator } from './mathUtils';

console.log(PI); // 3.14159
console.log(add(2, 3)); // 5

const calc = new Calculator();
console.log(calc.multiply(4, 5)); // 20

console.log(subtract(10, 4)); // 6

// 解构导入
import { format, parse as parseDate } from './utils';

import subtract from './mathUtils'; //默认导入
import {add,PI} from './mathUtils'; //命名导入
import * as MathUtils  from './mathUtils'; //全部导入
import { parse as parseDate } from './utils'; //重命名导入

仅导入类型(不生成运行时代码):

import type { Point } from './types';

4.模版解析策略

typescript支持两种主要的模块解析策略,由tsconfig.json中的moduleResolution选项控制:

class:旧版策略,现已不常用。

node:模拟Node.js的模块解析行为,查找顺序

  • 查找确切文件名(如:./utils.js)
  • 查找目录下的package.json中的main字段
  • 查找目录下的index.js文件

5.模块格式(Moudule Target)

  • tsconfig.json中的moudule选项指定编译后的javascript模块格式,常见值包括:
  • commonjs:用于Node.js环境。
  • es2015/es2020/esnext:用于现代浏览器或支持ES Modules的环境。
  • umd:通用模板定义,兼容多种环境。

6.路径映射(Path Mapping)

在tsconfig.json中配置路径别名,避免深层相对路径引用

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/components/*"],
      "@utils/*": ["src/utils/*"]
    }
  }
}

7.外部模板与生命文件

对于第三方(如 lodash,react),typescript通过.d.ts声明文件提供类型信息,通常通过npm安装对应的@types/xxx包。

npm install lodash
npm install --save-dev @types/lodash
import _ from 'lodash'
_.chunk([1,2,3,4],2)

8.动态导入(Dynamic import) 支持运行时按需加载模块,返回promise。

async function loadComponents(){
  const module = await import('./lazyComponent');
  module.render();
}

ts的模板系统基于es6模块语法,并增强了类型支持,合理使用可以帮助你

  • 实现代码解耦
  • 提高可测试性
  • 避免命名冲突
  • 支持懒加载和代码分割 要有效使用模块,建议结合tsconfig.json进行合理配置,并遵循一致的导入、导出规范。