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

Vite+React项目无法导入自定义库类型模块问题排查

问题排查:Vite中无法导入自研组件库的类型模块

问题描述

搭建基于Vite和React的应用,将自研组件库作为node模块引入。采用组件与类型分开导入的方式时,Vite报错:

Cannot find module 'library/types' or its corresponding type declarations.

该导入方式在create-react-app环境下可正常工作。

库相关配置信息

package.json中的类型导出配置

"typesVersions": {
    "*": {
        "types": [
            "./dist/lib/types/index.d.ts"
        ]
    }
}

库目录结构

|-package.json
|-src
|-dist
|   |-types
|   |-index.d.ts
|   |-lib.es.js
|   |-lib.umd.js
|   |-index.css

期望的类型导入方式

import type { ThemeTypes } from "library/types"

解决方案

1. 修正typesVersions路径映射

当前typesVersions配置中的路径与实际目录结构不匹配:配置指向./dist/lib/types/index.d.ts,但实际类型文件位于./dist/types/index.d.ts。修改后的配置如下:

"typesVersions": {
    "*": {
        "types": ["./dist/types/index.d.ts"]
    }
}

2. 确认Vite项目的TypeScript模块解析策略

在项目的tsconfig.json中,确保moduleResolution设置为"bundler"(Vite推荐)、"node16"或"nodenext",这些模式能正确解析typesVersions配置:

{
  "compilerOptions": {
    "moduleResolution": "bundler",
    // 其他编译配置...
  }
}

3. 验证类型文件的正确性

检查dist/types/index.d.ts是否存在,且正确导出了目标类型:

// dist/types/index.d.ts
export type ThemeTypes = {
  // 你的类型定义内容
};

4. 清理依赖缓存

执行以下命令清理缓存并重新安装依赖,避免缓存导致的解析异常:

rm -rf node_modules
rm package-lock.json
npm install

原因说明

create-react-app默认的TypeScript配置可能使用了较宽松的模块解析策略(如旧版的"node"模式),对typesVersions的兼容处理与Vite不同。Vite更严格遵循现代模块解析规范,因此需要确保路径映射和解析策略的正确性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:52:28