>我正在设置一个节点/打字稿服务器来构建一个实时应用程序。我的服务器和客户端位于同一文件夹中。
我想做的是在运行"server:dev"脚本时从打字稿编译器中排除"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.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",
}
}
动态更改编译器选项的一般方法:
由于fs
模块可以在 node.js 中使用,因此您可以将此 util 函数添加到 node.j sproject 中:
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 app 加载时为顶级,所以它会更新 tsconfig.json。 默认设置应为 "exclude": ["src/server"]
。当您在服务器上时,它将更改为 "exclude": ["src/client"]
使用此方法,您甚至可以将参数传递给函数,以便可以根据应用所需的特定设置更改 ts 编译器选项。