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

NX Monorepo中React应用如何正确导入共享React组件?

问题描述

我用NX创建集成式Monorepo,通过--js flag创建React应用后,把所有js文件改成了jsx;接着用对应命令加--js flag在libs目录创建共享组件,同样把所有js文件改成jsx。但启动服务时出现导入错误:

Executing task: npx nx run myapp:serve 

> nx run myapp:serve:development

  ➜  Local:   http://localhost:4200/
Error: The following dependencies are imported but could not be resolved:

  @demo-2/mylibrary (imported by /home/user/Desktop/demo-2/apps/myapp/src/app/app.jsx)

Are they installed?
    at file:///home/user/Desktop/demo-2/node_modules/vite/dist/node/chunks/dep-f7d05e3f.js:44138:23
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async file:///home/user/Desktop/demo-2/node_modules/vite/dist/node/chunks/dep-f7d05e3f.js:43547:38

我的tsconfig.base.json配置如下:

{
  "compileOnSave": false,
  "compilerOptions": {
    "rootDir": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "module": "esnext",
    "lib": [
      "es2020",
      "dom"
    ],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@demo-2/mylibrary": [
        "libs/mylibrary/src/index.jsx"
      ],
      "@myorg/is-even": [
        "libs/is-even/src/index.js"
      ],
      "odd": [
        "libs/odd/src/index.js"
      ],
      "odd2": [
        "libs/odd2/src/index.js"
      ]
    }
  },
  "exclude": [
    "node_modules",
    "tmp"
  ]
}
解决方法
  • 检查libs组件的package.json配置:进入libs/mylibrary目录,确保package.json的name字段是@demo-2/mylibrary,同时main或exports指向正确的jsx入口,示例配置:
    {
      "name": "@demo-2/mylibrary",
      "main": "./src/index.jsx",
      "type": "module"
    }
    
  • 调整Vite的解析配置:在应用根目录的vite.config.js中,添加jsx扩展名支持并确保NX路径插件生效:
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
    
    export default defineConfig({
      plugins: [react(), nxViteTsPaths()],
      resolve: {
        extensions: ['.mjs', '.js', '.jsx', '.json'],
      },
    });
    
  • 验证文件路径与拼写:确认libs/mylibrary/src/index.jsx文件真实存在,tsconfig.base.json中paths的路径拼写、大小写完全匹配实际文件路径。
  • 重启NX服务:停止当前运行的npx nx run myapp:serve进程,重新执行启动命令,确保所有配置修改生效。
  • 规范导入语句:在app.jsx中导入组件时,直接使用别名导入即可,无需加文件后缀,比如:import { MyComponent } from '@demo-2/mylibrary'。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:17:15