简体   繁体   中英

React Monorepo yarn workspaces + typescript + absolute imports

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM