使用打字稿在客户端和服务器之间共享代码

时间:2019-06-08 10:23:15

标签: typescript

所以我找到了这篇帖子Share interfaces between separat TypeScript projects,但没有得到答案,我现在面临着同样的问题,我在项目根目录中有一个客户端,服务器和共享文件夹,客户端和服务器都有根目录下的tsconfig和带有打字稿文件的src文件夹,我希望能够像

一样导入
import { PromotionInterface } from '@shared/Promotion';

但是使用下面的tsconfig却表明找不到模块

{
  "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"
  ]
}

有没有办法使这项工作成功?

1 个答案:

答案 0 :(得分:0)

您需要按照以下tsconfig错误中的指示将存储库的根目录指定为baseUrl

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

然后,您指定到基本URL的路径相对

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

我认为您不需要在includerootDir数组中包含共享文件夹路径。以下配置对我有用:

{
  "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"
  ]
}