Search code examples
javascriptreactjsvitemonorepo

How to properly import a shared external react component inside a react app in NX monorepo?


I am using NX to create an integrated monorepo . I created a react app using --js flag, then I changed the js files to jsx. After I created a shared component in libs folder using this command and the --js flag, I changed every js to jsx. However when I try to import I got this error:

  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

How can I solve this? I don't have any idea.

My tsconfig.base.json looks like this:

{
  "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"
  ]
}

Solution

  • In case someone needs it in the future I add my solution here:

    I create a new project using NX, I chose webpack as bundler. My NX initial setup looks like this:

    
     >  NX   Let's create a new workspace [https://nx.dev/getting-started/intro]
    
    ✔ Choose what to create                 · integrated
    ✔ What to create in the new workspace   · react-monorepo
    ✔ Repository name                       · repo_name
    ✔ Application name                      · app_name
    ✔ Bundler to be used to build the application · webpack
    ✔ Default stylesheet format             · scss
    ✔ Enable distributed caching to make your CI faster · No
    
    

    After I created a react component in JS with this command nx generate @nx/react:library mylibrary --js and also a new react app in js ( the default one comes in ts) with the --js flag.

    After I imported the mylibrary component in the new app and changed the file tsconfig.tools.json: I added js in the list of included files as follows: "include": [ "**/*.ts", "**/*.js" ]