Bharat Soni
Bharat Soni

Reputation: 2902

Unexpected import error in turborepo package

I am working on my first demo project with TurboRepo. Plan is to create a types named internal package which will share types to the UI as well as to the Server. I followed these steps to create types package:

{
  "name": "@repo/types",
  "type": "module",
  "private": true,
  "exports": {
    ".": "./index.ts"
  },
  "version": "1.0.0",
  "main": "./index.ts",
  "types": "./index.ts",
  "files": [
    "./index.ts"
  ],
  "scripts": {
    "dev": "tsc --watch"
  },
  "devDependencies": {
    "@types/node": "^20.8.10",
    "body-parser": "^1.20.2",
    "esbuild": "^0.19.5",
    "tsx": "^3.14.0",
    "typescript": "^5.5.4",
    "@repo/typescript-config": "workspace:*"
  },
  "dependencies": {
    "zod": "^3.22.4"
  }
}
{
  "$schema": "https://json.schemastore.org/tsconfig",
  "extends": "../typescript-config/nextjs.json",
  "compilerOptions": {
    "outDir": "dist"
  },
  "include": [
    "**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

If I use "extends": "@repo/typescript-config/nextjs.json", in extends, then it throws an error, so I used the relative path.

Now the problem is when I import types from the package, TS throws an error saying

typescript: Cannot find module '@repo/types' or its corresponding type declarations. [2307]

The app works as expected, but I am unable to fix this TS error. I'm not sure what am I missing here. Could you please guide me in the right direction?

TS shouldn't show the 2307 error.

I have added types package in web app like this:

"@repo/types": "workspace:*",

and importing the type like this:

import type { InventoryItem } from "@repo/types";

Upvotes: -1

Views: 296

Answers (1)

Vladyslav Sokolov
Vladyslav Sokolov

Reputation: 16

  1. Make sure your root package.json includes the workspace configuration:

{
  "workspaces": [
    "packages/*"
  ]
}

  1. In your types package, try adding "type": "module" to your package.json and ensure you have these fields:

{
  "name": "@repo/types",
  "types": "./index.ts",
  "main": "./index.ts",
  "sideEffects": false
}

3.Make sure your root tsconfig.json (at the monorepo root) includes paths configuration:

{
  "compilerOptions": {
    "paths": {
      "@repo/types": ["./packages/types"]
    }
  }
}

  1. In your web app's tsconfig.json, make sure you have:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@repo/types": ["../types"]
    }
  }
}

  1. Also, verify that your project structure follows this pattern:

root/
  ├── packages/
  │   ├── types/
  │   │   ├── index.ts
  │   │   ├── package.json
  │   │   └── tsconfig.json
  │   └── web/
  │       ├── package.json
  │       └── tsconfig.json
  ├── package.json
  └── tsconfig.json

Upvotes: 0

Related Questions