首页 > 解决方案 > 我可以从 ts 编译器中动态排除文件吗?

问题描述

我正在设置一个节点/打字稿服务器来构建一个实时应用程序。我的服务器和客户端在同一个文件夹中。

我想要做的是在我运行“server:dev”脚本时从 typescript 编译器中排除“src/client”,当我运行“client:dev”时排除“src/server”。

我已经尝试找到一种从命令行中排除文件的方法,但我没有找到解决方案。

这就是我的 tsconfig.json 的样子

{
  "compilerOptions": {
    "target": "es6",                          
    "module": "commonjs",                     
    "lib": ["dom","es2017"],                  
    "sourceMap": true,
    "outDir": "dist",                         
    "strict": true,                           
    "noImplicitAny": true,                     
    "moduleResolution": "node",                  
    "esModuleInterop": true,                     
    "resolveJsonModule": true                 
  },
  "exclude": [
      "src/client"
  ]
}

但是当我运行客户端时,我需要包含“src/client”并排除“src/server”。

标签: node.jsreactjstypescript

解决方案


tsconfig.jsonsupportextends字段,在您的情况下,您应该将公共配置放在 base中,然后分别为客户端和服务器tsconfig.json创建 tsconfig 。extends

// tsconfig.json
{
  "compilerOptions": {
    ...               
  }
}

// tsconfig.client.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    ...               
  },
  "exclude": ["src/server"]
}

// tsconfig.server.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    ...               
  },
  "exclude": ["src/client"]
}

对于 npm 脚本:

// package.json
{
  "scripts": {
    "server:dev": "tsc --build tsconfig.server.json",
    "client:dev": "tsc --build tsconfig.client.json",
  }
}

推荐阅读