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

如何配置TypeScript包以无需打包器直接导入使用?

问题与解决方案

问题场景

我有一个小型npm包@nomatter/utils,相关配置如下:

package.json内容

{
  "name": "@nomatter/utils",
  "license": "MIT",
  "author": "Dave Stein",
  "version": "0.0.1",
  "scripts": {
    "tsc:watch": "tsc --watch --preserveWatchOutput"
  },
  "type": "module",
  "main": "out-tsc/src/index.js",
  "types": "out-tsc/src/index.d.ts",
  "dependencies": {
    "typescript": "^4.9.5",
    "yup": "^0.32.11"
  },
  "devDependencies": {},
  "description": ""
}

包内TypeScript配置(含declaration)

{
  "compilerOptions": {
    "target": "es2018",
    "module": "esnext",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "lib": ["es2017", "dom"],
    "strict": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "outDir": "out-tsc",
    "sourceMap": true,
    "inlineSources": true,
    "rootDir": "./",
    "incremental": true,
    "declaration": true
  },
  "include": ["**/*.ts"],
}

核心问题

包编译后,out-tsc/src/index.js和out-tsc/src/index.d.ts均正确生成(index.ts仅导出signupSchema),但在应用中执行import '@nomatter/utils'时,TSC报错无法解析该导入,不确定main和types字段的配置是否正确。


解决步骤

1. 补充exports字段(关键修复)

由于包启用了"type": "module",Node.js和TypeScript的模块解析逻辑会优先读取exports字段,而非单独的main/types。添加该字段可明确指定入口文件:

{
  // ...其他原有配置
  "type": "module",
  "main": "out-tsc/src/index.js",
  "types": "out-tsc/src/index.d.ts",
  "exports": {
    ".": {
      "import": "./out-tsc/src/index.js",
      "types": "./out-tsc/src/index.d.ts"
    }
  },
  // ...其他原有配置
}

该配置直接告诉TS和Node.js,当导入@nomatter/utils时,应该加载的JS文件和类型定义文件。

2. 验证包的本地安装/链接状态

  • 本地开发测试时,确保已通过npm link或yarn link将包关联到应用,或在应用的package.json中使用本地路径依赖(例如"@nomatter/utils": "file:../path/to/utils-package")。
  • 完成链接后,重启应用的TypeScript服务(如VSCode中按Ctrl+Shift+P执行TypeScript: Restart TS Server),避免缓存导致的解析异常。

3. 检查应用的TS配置

确保应用的tsconfig.json中,moduleResolution设置为node或bundler(适配Vite/Webpack等打包工具),且未开启allowImportingTsExtensions(除非直接导入.ts文件,此处不适用)。

4. 确认编译产物路径

手动进入包的根目录,检查out-tsc/src/index.js和out-tsc/src/index.d.ts是否存在,路径与package.json中的配置完全一致。

5. 可选:简化types字段(非必须)

若类型文件与JS文件同目录同名,可将types字段简化为"types": "out-tsc/src/index",TS会自动识别.d.ts后缀,但显式写全路径兼容性更好。


内容的提问来源于stack exchange,提问作者Dave Stein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:40:30