在tsconfig.json中选项“importsNotUsedAsValues”已删除。请从配置中删除它。 请改用“verbatimModuleSyntax”
时间: 2025-04-07 11:14:35 浏览: 105
### 如何在 `tsconfig.json` 中替换已删除的 `importsNotUsedAsValues` 并改用 `verbatimModuleSyntax`
随着 TypeScript 5.0 的发布,`importsNotUsedAsValues` 已被废弃并建议使用新的 `--verbatimModuleSyntax` 选项替代。以下是具体配置方法以及其作用:
#### 配置说明
1. **启用 `verbatimModuleSyntax`**
在 `tsconfig.json` 文件中的 `compilerOptions` 下新增或设置 `"verbatimModuleSyntax": true` 即可开启此功能[^2]。
```json
{
"compilerOptions": {
"verbatimModuleSyntax": true,
"module": "ESNext",
"target": "es2016"
}
}
```
2. **行为变化**
启用该选项后,TypeScript 编译器会按照以下规则处理导入语句:
- 所有未加 `type` 修饰符的导入/导出会保持原样不作改动。
- 加上 `type` 修饰符的导入/导出会被完全移除。
示例代码展示效果如下:
```typescript
// 原始代码
import type { A } from "a";
import { b, type c, type d } from "bcd";
import { type xyz } from "xyz";
// 经过编译后的结果
// 完全被删除
// import type { A } from "a";
// 被重写为 'import { b } from "bcd";'
import { b } from "bcd";
// 被重写为 'import {} from "xyz";'
import {} from "xyz";
```
3. **注意事项**
如果项目依赖于旧版 `importsNotUsedAsValues` 行为,则需要逐步调整代码逻辑以适应新规则。特别是对于仅用于类型检查而无实际运行时意义的导入,应显式加上 `type` 关键字标记。
4. **初始化配置文件**
若尚未创建 `tsconfig.json` 或需重新生成默认模板,可通过命令行工具快速完成操作[^4]:
```bash
npx tsc --init
```
此过程将自动生成一份基础配置文档供开发者进一步定制化修改。
---
### 示例代码片段
假设我们有一个简单的 TypeScript 源码文件需要用到上述特性:
```typescript
// before.ts
import type { SomeInterface } from "./interfaces";
import { someFunction, type AnotherInterface } from "./utils";
someFunction();
```
对应的 tsconfig 设置如下所示:
```json
{
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"verbatimModuleSyntax": true,
"module": "ESNext",
"target": "es2016"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
```
经过编译之后的结果将是这样的形式:
```javascript
// dist/before.js (after compilation)
import { someFunction } from './utils';
someFunction();
```
可以看到只有真正参与执行流程的部分得以保留下来,其余无关紧要的信息均已被妥善清理掉。
---
阅读全文