Skip to content

声明文件(用的少)

使用场景

  • 原来是 js 文件想在 ts 文件中使用

根目录/src 目录下面 创建声明文件

  • global.d.ts (global 可以起任意名字,但是必须用 .d.ts 结尾) 我这里就起了个 axios,注意必须有declare
ts
declare module "MyCustom" {
  export interface GlobalInterface {
    get: (url: string) => string;
    post: (url: string, data: any) => string;
  }
}

使用

  • src/demo/index.ts
ts
import { GlobalInterface } from "MyCustom";
let GlobalAxios: GlobalInterface;

GlobalAxios = {
  get: (url: string) => {
    console.log(url);
    return "GET response";
  },
  post: (url: string, data: any) => {
    console.log(url);
    return "POST response";
  },
};

GlobalAxios.get("https://api.example.com/data");
GlobalAxios.post("https://api.example.com/data", { key: "value" });

配置文件

  • tsconfig.json
json
{
  "compilerOptions": {
    /* 语言与环境 */
    "target": "ES2020", // 编译后的 JS 版本 (ES2020 比较现代)
    "module": "commonjs", // 模块系统 (Node.js 项目通常用 commonjs)
    "lib": ["ES2020"], // 引入的库定义

    /* 输出配置 */
    "outDir": "./dist", // 编译后的 JS 文件存放目录
    "rootDir": "./src", // 源代码 (.ts 文件) 的根目录
    "removeComments": true, // 编译时删除注释
    "noEmitOnError": true, // 报错时不生成编译文件

    /* 类型检查 (严格模式) - 建议开启,能帮你找错 */
    "strict": true, // 启用所有严格类型检查选项
    "esModuleInterop": true, // 允许 import 导入 CommonJS 模块
    "skipLibCheck": true, // 跳过对库文件的类型检查 (加快编译速度)
    "forceConsistentCasingInFileNames": true // 强制文件名大小写一致
  },
  "include": ["src/**/*"], // 只编译 src 目录下的文件
  "exclude": ["node_modules"] // 排除 node_modules 目录
}