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

如何解决Vite构建的TS npm包类型无法被导入的问题?

TS函数NPM包类型无法在依赖仓库中加载

我正在开发一个包含多个TypeScript函数的NPM包,将用于团队内的移动端和Web应用仓库。团队统一使用Vite作为构建工具,因此该包也基于Vite搭建。

当前配置文件

vite.config.ts

import { defineConfig } from 'vite'
import dts from 'vite-plugin-dts'

export default defineConfig({
  build: {
    lib: { // 必须配置,因为这是类库,没有index.html入口
      name: 'project-name',
      entry: './src/index.ts',
      fileName: 'index',
      formats: ['cjs', 'umd'] // 不确定这行的作用,但它帮我生成了dist里的index.js和index.umd.js
    },
    outDir: 'dist'
  },
  plugins: [
    dts({
      insertTypesEntry: true // 不加这行的话,根本不会生成index.d.ts
    })
  ]
})

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "strict": true,
    "sourceMap": true,
    "declaration": true,
    "outDir": "dist",
    "declarationDir": "dist",
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

package.json 路径配置片段

{
  ...,
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "module": "./dist/index.umd.js",
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "require": "./dist/index.umd.js"
    }
  },
  "scripts": {
    "build": "vite build"
  },
  ...
}

问题现状

将这个包安装到其他仓库后,类型完全无法被识别,所有类和函数都被标记为any类型,VS Code中导入的内容也显示为any。类型信息对我来说非常关键,必须解决这个问题。

已尝试的解决方法

  • 替换插件:用vite-tsconfig-paths替代vite-plugin-dts,但dist文件夹中没有生成任何.d.ts文件
  • 调整tsconfig:修改了tsconfig的多项配置,但感觉vite-plugin-dts并没有识别到根目录下的tsconfig.json

补充细节

  • 类型均使用export type ...语法导出
  • src/index.ts中已经导入并导出了所有内容(包括类型)
  • 当前构建生成的index.d.ts仅包含一行代码:
export * from './index'

这相当于循环导出,完全没有实际的类型定义内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:23:10