React Monorepo yarn workspaces + typescript + absolute imports
Asked Answered
S

1

10

I'm having issues setting up an React project with yarn workspaces and typescript. My folder structure is:

-root
 -package.json
 -workspaces
  -web
  -common

and my package.json file is:

{
  "name": "my-project-name",
  "private": true,
  "workspaces": [
  "workspaces/web",
  "workspaces/common"
  ],
  "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
}

My issue is: when I import files on web from the common project, it works fine if it's a .js file, but fails with TypeError: Object(...) is not a function when using .ts or .tsx files.

Any ideas on what I might be missing?

Smelter answered 24/5, 2018 at 15:58 Comment(2)
Same issue here, I'd love to have an answer!Deadbeat
1 year later, still searching for answerGravedigger
S
2

I recommend adopting the following file hierarchy:

- root
- package.json
- tsconfig.json
- packages 
  - common
    - package.json
    - tsconfig.json 
- services
  - web
    - package.json
    - tsconfig.json

Everything in the packages folder can be imported. Services are "leaf" projects that you don't want to import in other projects.

With that as a base, your root package.json should be setup like that:

{
"name": "my-project-name",
  "private": true,
  "workspaces": [
    "packages": [
      "packages/*",
      "services/**/*"
    ],
  ],
}

Then, you also need to tell typescript how to resolve the imports.

In the root tsconfig.json, set the following:

{
"compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@myproject/*": ["packages/*/src"]
    },
}

Make sure that every tsconfig extends this base with "extends": "../../tsconfig.json"

Inside web/package.json or any package that needs to import common, define common as a dependency:

{
  [...]
  "dependencies": {
    "@myproject/common": "*",
  }
}

Now if your common package.json has a name set to `"@myproject/common", you can import your code inside web with :

import { myUtilFunction } from "@myproject/common";

I would advise you to also use learn with a setup like this. You will also need to modify a bit your build pipeline, since you're importing files inside /web that are outside the /web folder. For a more complete example, you can check out this repo: https://github.com/NiGhTTraX/ts-monorepo

Soledadsolely answered 19/4, 2021 at 18:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.