具有两个输出目录的TypeScript共享代码库

时间:2019-04-18 14:14:04

标签: javascript node.js typescript

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

重要:“共享”文件夹需要在 srv app 中生成,否则我们的核心系统会崩溃。

我已经进入src目录,其中客户端包含client.ts,服务器包含server.ts,共享包含index.ts。现在我要在client.ts和server.ts中使用共享。

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

server / 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"
        }
    ]
}

shared / tsconfig.json

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

PS:如果有更好的解决方案来解决此问题。请让我知道:)

亲切的问候, 塞巴斯蒂安

2 个答案:

答案 0 :(得分:1)

您可以尝试将/ shared文件夹转换为单独的npm软件包,然后使用npm link / npm install将它们共享到每个项目中吗?我使用TypeScript对React和React Native进行了类似的操作。

答案 1 :(得分:1)

Typescript编译过程不会为您移动或追加文件。它只是为.ts文件创建.js文件。仅使用tsc,就无法创建包。

您应该使用像webpack这样的捆绑器 这是一个可能有用的链接:https://webpack.js.org/guides/typescript/


话虽如此,我认为你想做的是不正确的。我假设您的客户端是一个单页应用程序,而服务器是一个节点服务器来服务那些文件? 如果是这样,您将在节点环境中运行服务器并提供client.js。

您可以捆绑client.js(与webpack或其他cli工具一起使用),并直接从server.js提供服务。除非您仅将服务器目录复制到某个位置,否则Server.js无需将shared.js或client.js放在同一目录中。


编辑:PS:在大型项目中有针对此类用例的monorepo方法。我建议看看“纱线工作区”和“ lerna”