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

发布至npm的user-credits库无法被其他项目正常引入,本地依赖正常但远程依赖报TS2307错误

发布至npm的user-credits库无法被其他项目正常引入,本地依赖正常但远程依赖报TS2307错误

兄弟我太懂你这种折腾一整天的崩溃感了!本地用相对路径引用库完全没问题,一发布到npm就各种报错,核心原因大概率是你的user-credits库本身的打包配置或package.json关键字段没做好,导致npm包没有正确暴露模块入口和类型声明文件。我帮你梳理几个必查的关键点:

1. 先检查库的package.json核心配置

这是本地和远程依赖差异的核心——本地依赖时TypeScript能直接读取源码里的类型和模块,但远程npm包必须通过package.json明确告诉工具链:入口文件在哪?类型文件在哪?

你需要确保库的package.json里有这些字段:

  • types/typings字段:这是解决TS2307错误的关键!必须指定类型声明文件的入口,比如:
    "types": "./dist/index.d.ts"
    
  • main/module字段:指定不同模块系统的入口文件,如果你的库是ES模块(和测试项目的"type": "module"一致),可以这么配:
    "main": "./dist/index.js",
    "module": "./dist/index.js"
    
  • exports字段(更现代的配置):如果需要同时支持CommonJS和ES模块,或者更精细的入口控制,推荐用这个:
    "exports": {
      ".": {
        "import": "./dist/index.js", // ES模块入口
        "require": "./dist/index.cjs", // CommonJS入口
        "types": "./dist/index.d.ts" // 类型入口
      }
    }
    
  • type字段:如果你的库用ES模块,一定要加上"type": "module",否则会和CommonJS模块系统冲突,这很可能就是你SvelteKit里ReferenceError: exports is not defined的元凶!

2. 确认类型文件和编译产物被正确发布

光配置字段还不够,得确保这些文件真的被传到npm上:

  • 检查库的tsconfig.json,必须开启declaration: true,这样TypeScript才会生成.d.ts类型文件:
    {
      "compilerOptions": {
        // ...其他配置
        "declaration": true, // 生成类型声明文件
        "declarationMap": true, // 可选,方便调试类型
        "outDir": "dist" // 编译产物输出目录
      }
    }
    
  • 用files字段明确指定要发布的文件(比.npmignore更可靠),避免不小心把dist目录或类型文件排除在外:
    "files": [
      "dist",
      "README.md",
      "package.json"
    ]
    

3. 本地验证远程包的实际内容

安装远程包后,去测试项目的node_modules/user-credits目录里看看:

  • 有没有dist文件夹?
  • 文件夹里有没有index.js(或你指定的入口文件)和index.d.ts?
    如果没有,说明你打包时没生成这些文件,或者发布时漏传了——这时候得回去检查库的打包脚本和发布流程。

4. 解决SvelteKit里的exports is not defined错误

这个错误本质是模块系统不兼容:如果你的库输出的是CommonJS模块,但SvelteKit默认使用ES模块,就会出现这个报错。解决办法:

  • 确保库的package.json设置了"type": "module",同时打包出ES模块产物;
  • 或者用exports字段分别为import和require指定不同的入口,让SvelteKit能正确识别ES模块。

给你一个示例的库配置参考

库的package.json

{
  "name": "user-credits",
  "version": "0.9.4-alpha",
  "type": "module",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "types": "./dist/index.d.ts"
    }
  },
  "files": [
    "dist"
  ],
  "scripts": {
    "build": "tsc"
  },
  "devDependencies": {
    "typescript": "^5.2.2"
  }
}

库的tsconfig.json

{
  "compilerOptions": {
    "moduleResolution": "node",
    "target": "ESNext",
    "module": "ESNext",
    "outDir": "dist",
    "rootDir": "src",
    "declaration": true,
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

按照这些步骤排查和调整,应该能同时解决TS2307和SvelteKit里的exports错误。本地能用只是因为TypeScript直接读取了源码,而npm包需要把编译后的产物和类型文件正确暴露出来才行~

备注:内容来源于stack exchange,提问作者Zied Hamdi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 10:39:34