Cam Jackson
Cam Jackson

Reputation: 12304

Create-react-app absolute imports don't work with yarn v2 workspaces + typescript

I'm using yarn v2 workspaces, and one of my workspaces is a frontend built with create-react-app / react-scripts. I want to enable absolute imports within the frontend app, so I can do things like import Button from 'components/Button' instead of import Button from '../../../components/Button'. Note that my issue is not to do with cross-workspace imports.

I've followed the instructions in the CRA docs for enabling absolute imports, and everything is working except for tsc:

This also results in red squigglies under the import statement in my editor (vscode).

My project structure is like this:

package.json
tsconfig.json
workspaces/
  - backend
  - frontend
    - package.json
    - tsconfig.json
    - src/
      - components/Button.tsx
      - pages/PageWithAButton.tsx

Here's the root tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true
  }
}

And the frontend tsconfig.json

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "jsx": "react-jsx",
    "baseUrl": "src"
  },
  "include": ["src"],
  "references": [{ "path": "../shared" }]
}

I invoke tsc using this command from the root directory:

yarn tsc --noEmit --jsx preserve

How can I make tsc resolve the absolute import?

Upvotes: 1

Views: 1585

Answers (2)

Viktor Vlasenko
Viktor Vlasenko

Reputation: 2532

According to Yarn 2+ documentation the link protocol is recommended over aliases and (TypeScript) path mapping: https://yarnpkg.com/features/protocols#why-is-the-link-protocol-recommended-over-aliases-for-path-mapping

It is better to remove paths from your tsconfig.json and instead add to package.json:

"dependencies": {
  ...
  "components": "link:./src/components"
}

After that you should run

yarn

for changes to package.json to take effect

Upvotes: 3

Viet
Viet

Reputation: 12807

In compilerOptions of tsconfig.json , you add path like this:

"paths": {
  "components/*": ["src/components/*"]
}

Upvotes: 0

Related Questions