【问题标题】:Share code between client and server in typescript在打字稿中在客户端和服务器之间共享代码
【发布时间】:2019-06-08 10:23:15
【问题描述】:

所以我找到了这篇帖子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"
  ]
}

有没有办法让它工作?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您需要将存储库的根指定为baseUrl,按照以下 tsconfig 错误的说明:

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

    然后,您指定路径 relative 到基本 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"
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-11
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      相关资源
      最近更新 更多