我有几个我想用脚本编译的文件.这些文件依赖于paths编译选项来解析其模块.因为我想特别针对这些文件,所以我必须提供它们tsc(因为我不想tsconfig.json为这个任务创建一个单独的目标文件)
我已经查看了将--path参数传递给的选项tsc,但是这是不允许的(error TS6064: Option 'paths' can only be specified in 'tsconfig.json' file.)
.ts在使用该paths选项时,我能以某种方式仅编译特定文件吗?
更新(22-06-17)
根据要求,一些具体的例子:
tsconfig.json文件中的相关设置如下:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"Components/*": [
"./src/Components/*"
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以相关部分是路径设置,您可以在其中创建缩写以从某个目录导入文件.所以你可以import {header} from 'Components/header.ts'代替导入一个文件import {header} from '../../Components/header.ts'
但我需要从命令行编译特定的文件.但如果我尝试:
tsc --project tsconfig.json entryFile.ts
Run Code Online (Sandbox Code Playgroud)
它会给我错误:
error TS5042: Option 'project' cannot be mixed with source files on a command line.
Run Code Online (Sandbox Code Playgroud)
如果我尝试为pathscli 提供选项,我会收到以下错误:
error TS6064: Option 'paths' can only be specified in 'tsconfig.json' file.
Run Code Online (Sandbox Code Playgroud)
Bra*_*ram 13
在命令行上指定输入文件会使tsconfig.json无效.
在命令行中指定输入文件时,将忽略tsconfig.json文件.
来自TypeScript文档.
因此,没有其他选择,只能使用tsconfig.json与文件的正确"包含"(或排除)规范.好消息是,在相同的文档中,您会发现:
tsconfig.json文件可以使用extends属性从其他文件继承配置.
所以你可以做的是用这样的东西覆盖你的tsconfig的include属性:
{
"extends": "./tsconfig.json",
"include": [
"src/root/index.ts"
]
}
Run Code Online (Sandbox Code Playgroud)
所以你可以创建一个脚本:
tsc与--project指定为临时tsconfig有人可能会说这非常复杂,并质疑为什么他们决定不正确支持这种情况.但是,问题仍然是为什么人们只想编译项目的一个文件.在开发时,您可以使用watch(-w)选项来编译更改文件,在构建完整项目时,您可能希望完全编译完整项目.
我也有类似的需求,需要确保项目将使用lint-staged 进行编译。如果tsconfig.json允许 和 文件路径的组合,则可以"tsc"直接用作 lint-staged 命令。
作为一种解决方法,我创建了以下帮助脚本scripts/tsc-lint.sh:
#!/bin/bash -e
TMP=.tsconfig-lint.json
cat >$TMP <<EOF
{
"extends": "./tsconfig.json",
"include": [
EOF
for file in "$@"; do
echo " \"$file\"," >> $TMP
done
cat >>$TMP <<EOF
"unused"
]
}
EOF
tsc --project $TMP --skipLibCheck --noEmit
Run Code Online (Sandbox Code Playgroud)
然后 lint-staged 配置包含:
"lint-staged": {
"{src,tests}/**/*.ts": [
"scripts/tsc-lint.sh"
]
},
Run Code Online (Sandbox Code Playgroud)
文件.tsconfig-lint.json被添加到.gitignore.
只是为了建立在@Bram 的回答之上......
我在我的项目中做的是有两个 tsconfigs:
project/
dist/
docs/
src/
package.json
tsconfig.json
tsconfig-build.json
Run Code Online (Sandbox Code Playgroud)
所以我有一个tsconfig-build.json(因为我不想docs/包含在我的构建中):
// tsconfig-build.json
{
"extends": "./tsconfig.json",
"include": [
"src/**/*"
]
}
Run Code Online (Sandbox Code Playgroud)
然后你可以有一行package.json:
// package.json
...
"scripts": {
...
"build": "tsc --p tsconfig-build.json"
},
Run Code Online (Sandbox Code Playgroud)
--noResolve是这里的关键: https: //www.typescriptlang.org/tsconfig/#noResolve
举个例子:
// tsconfig.myFile.json
{
// "extends": "./tsconfig.json",
"include": [
"myFile.ts"
],
"compilerOptions": {
"noResolve": true
}
}
Run Code Online (Sandbox Code Playgroud)
$ tsc --project tsconfig.myFile.json
还有一些方法可以包含--noResolve一些输出标志来仅使用命令行来完成此操作。
| 归档时间: |
|
| 查看次数: |
14579 次 |
| 最近记录: |