【问题标题】:Can i exclude files dynamically from ts compiler?我可以从 ts 编译器中动态排除文件吗?
【发布时间】:2019-08-23 20:04:27
【问题描述】:

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

我想要做的是在我运行“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”。

【问题讨论】:

  • 你可以有两个 tsconfig 文件(可以扩展通用的)

标签: node.js reactjs typescript


【解决方案1】:

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

// 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",
  }
}

【讨论】:

    【解决方案2】:

    动态更改编译器选项的一般方法:

    由于 fs 模块可以在 node.js 中使用,你可以在你的 node.js 项目中添加这个 util 函数:

    const fs = require("fs")
    const prettier = require("prettier")
    
    function changeTs(){
        // this guarantees that I am on server
        if(typeof window === "undefined"){
          // process.cwd returns base folder, current working directory
          // whatever path is
          const tsPath = path.join(process.cwd(), "tsconfig.json")
          const tsConfig = require(tsPath)
          tsConfig.compilerOptions.exclude = ["src/client"]
           fs.writeFileSync(
               tsPath,
               prettier.format(
               JSON.stringify(tsConfig), { parser: "json" }
                 )
               )
        
          }  
      }
    

    调用上面的函数,在 node.js 应用加载的时候顶层,所以它的 tsconfig.json 会被更新。默认设置应为"exclude": ["src/server"]。当您在服务器上时,它将更改为 "exclude": ["src/client"]

    使用这种方法,您甚至可以将参数传递给函数,因此您可以根据应用所需的特定设置更改 ts 编译器选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-05
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      • 2016-04-06
      相关资源
      最近更新 更多