Share code between client and server in typescript

Viewed 717

So I found this post Share interfaces between separat TypeScript projects but it did not get a answer, I am facing the same problem now, I have a client, server and shared folder inside the root of my project, both client and server have a tsconfig in their roots and a src folder with typescript files, I would like to be able to import like

import { PromotionInterface } from '@shared/Promotion';

But using the tsconfig below it says that it can not find the module

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "rootDirs": [
      "src",
      "../shared"
    ],
    "paths": {
      "@shared/*": [
        "../shared/*"
      ]
    },
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": [
    "src"
  ]
}

Is there a way to make this work?

1 Answers

You need to specify the root of your repository as baseUrl, as instructed in the following the tsconfig error:

Option 'paths' cannot be used without specifying '--baseUrl' option.ts

You then specify your paths relative to the base URL.

"baseUrl": "../",
"paths": {
  "@shared/*": [
    "shared/*"
  ]
},

I don't think you need to include the shared folder path in the include or rootDir arrays. The following config worked for me:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "rootDirs": [
      "src"
    ],
    "baseUrl": "../",
    "paths": {
      "@shared/*": [
        "shared/*"
      ]
    },
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": [
    "src"
  ]
}
Related