首页 > 解决方案 > 具有两个输出目录的 TypeScript 共享代码库

问题描述

我遇到了一个问题:/我希望共享代码库“共享”在两个目录中。打字稿本身可以做到这一点,还是我需要一些额外的构建任务?有更好的解决方案吗?

重要提示:“shared”文件夹需要在srvapp中生成,否则我们的核心系统会崩溃。

我有以下src目录,其中客户端包含 client.ts,服务器包含 server.ts,共享包含 index.ts。现在我想在client.ts和server.ts中使用shared。

src
   - client
     - client.ts
     - tsconfig.json
   - server
     - server.ts
     - tsconfig.json
   - shared
     - index.ts
     - tsconfig.json

如果我正在编译我的 TypeScript,应该会生成以下输出。

app
   - client
     - client.js
   - shared
     - index.ts
srv
   - server
     - server.js
   - shared
     - index.ts

这是我对每个目录 client/tsconfig.json的配置

{
    "compileOnSave": true,
    "compilerOptions": {
        "target": "es2018",
        "module": "commonjs",
        "noImplicitAny": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "outDir": "../../app",
        "sourceMap": true,
        "diagnostics": true,
    },
    "include": [
        "client.ts"
    ],
    "references": [
        { "path": "../shared"}
    ]
}

服务器/ts.config.json

{
    "compileOnSave": true,
    "compilerOptions": {
        "target": "es2018",
        "module": "commonjs",
        "noImplicitAny": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "outDir": "../../srv",
        "sourceMap": true,
        "diagnostics": true,
    },
    "include": [
        "server.ts"
    ],
    "references": [
        {
            "path": "../shared"
        }
    ]
}

共享/tsconfig.json

{
    "compilerOptions": {
      "declaration": true, 
      "declarationMap": true,
      "composite": true,     
    },
    "include": [
      "*.*"
    ],
    "references": []
}

PS:如果有更好的解决方案来解决这个问题。请告诉我 :)

亲切的问候,塞巴斯蒂安

标签: javascriptnode.jstypescript

解决方案


您可以尝试将 /shared 文件夹转换为单独的 npm 包,然后在每个单独的项目中使用npm link/npm install将它们连接在一起?我使用 TypeScript 对 React 和 React Native 做了类似的事情。


推荐阅读