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

React Monorepo中JS/TS混合项目模块声明文件缺失解决方案咨询

问题:React Monorepo中TS项目导入混合JS/TS组件库的类型兼容问题

背景

  • 正在搭建React monorepo,包含共享组件库与工具库,供多个业务项目复用
  • 组件库目前是JS/TS混合代码,正逐步迁移至TypeScript,需要同时兼容新的TS组件和旧的JS组件
  • 在非TypeScript的React项目中,导入共享组件后能正常获得IntelliSense提示与类型支持:TS组件提供原生类型,JS组件可自动生成类型
  • 但通过标准Vite初始化的TypeScript版React项目,导入组件时会出现类型错误

相关配置

TS React项目的tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "declaration": true
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

组件库的Babel配置

module.exports = {
  presets: [
    [
      "@babel/preset-typescript",
      {
        targets: {
          node: "current",
        },
      },
    ],
    [
      "@babel/preset-react",
      {
        isTsx: true,
      },
    ],
  ],
};

组件库的Webpack配置

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  mode: "production",
  entry: {
    index: { import: "./index.js" },
  },
  externals: {
    react: "react",
    "react-dom": "react-dom",
  },
  resolve: {
    extensions: [".js", ".jsx", ".ts", ".tsx"],
  },
  plugins: [new MiniCssExtractPlugin()],
  module: {
    rules: [
      {
        exclude: /node_modules/,
        loader: "babel-loader",
      },
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  output: {
    filename: "components.bundle.min.js",
    library: "webclientappsComponents",
    libraryTarget: "umd",
    umdNamedDefine: true,
    clean: true,
  },
};

已尝试的解决方案

  • 在TS项目的tsconfig.json中设置allowJs和checkJs,未解决问题
  • 在TS项目根目录创建typings.d.ts并声明全局module "*",虽能消除错误但完全丢失类型与IntelliSense支持

诉求

希望无需手动声明所有类型,实现与非TS项目一致的类型提示与智能感知效果


内容的提问来源于stack exchange,提问作者Štěpán Novotný

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:43:28