You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置TypeScript库实现类型与值的单语句导入

解决方案

要实现单语句同时导入类型与值,需要从库的编译配置、package.json声明两方面调整,具体步骤如下:

1. 配置package.json的入口与类型指向

  • 首先在package.json中明确指定类型定义文件的路径:
    {
      "name": "mylib",
      "main": "index.js", // 对应编译后的JS文件路径
      "types": "index.d.ts", // 对应编译后的类型定义文件路径
      "type": "module" // 如果库采用ES模块规范,添加该字段;CommonJS则省略
    }
    
  • 若你的项目使用Node.js 16+的模块解析模式(moduleResolution: "node16"或"nodenext"),需通过exports字段更精确地声明各环境的入口,包括类型:
    {
      "exports": {
        ".": {
          "import": "./index.js",
          "require": "./index.cjs", // 若提供CommonJS版本则添加
          "types": "./index.d.ts"
        }
      }
    }
    
    注意:如果编译产物输出到dist等子目录,需同步修改上述路径(例如"./dist/index.js")。

2. 调整TypeScript编译配置(tsconfig.json)

确保编译配置正确生成包含所有导出的类型定义文件:

{
  "compilerOptions": {
    "target": "ESNext", // 根据需要选择目标版本
    "module": "ESNext", // 与库的模块规范匹配
    "declaration": true, // 必须开启,用于生成.d.ts文件
    "declarationMap": false, // 可选,关闭类型映射文件以减少产物体积
    "outDir": "./dist", // 指定编译产物输出目录
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

编译后检查index.d.ts,确认同时包含类型与值的导出:

export type MyType = { /* 类型定义 */ };
export declare const myObj: MyType;

3. 消费项目的模块解析配置

确保消费项目的tsconfig.json中moduleResolution与库的模块规范匹配:

  • 库为ES模块时,设置moduleResolution: "node16"或"bundler"
  • 库为CommonJS时,设置moduleResolution: "node"

完成以上配置后,即可在消费项目中使用单语句导入:

import { myObj, MyType } from 'mylib';

内容的提问来源于stack exchange,提问作者Maksim Nesterenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 06:35:22