TypeScript 5.3 引入了对 导入属性 的支持。构建 ESM 项目时,编译器允许使用命名导入,但我不知道有任何 JavaScript 运行时支持此功能。 TypeScript 是否应该向下编译或禁止从 JSON 导入进行命名导入?
index.ts
import {compilerOptions} from './tsconfig.json' with {type: 'json'};
console.log(compilerOptions);
tsconfig.json
{
"compilerOptions": {
"target": "ES2023",
"lib": ["ES2023"],
"module": "NodeNext",
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"strict": true
}
}
package.json
{
"type": "module",
"devDependencies": {
"@types/node": "^22",
"typescript": "^5.5"
}
}
使用 Node.js 22.6.0 和 TypeScript 5.5.4 测试构建。
使用
npx tsc
进行编译不会产生警告或错误并输出 index.js
:
import { compilerOptions } from './tsconfig.json' with { type: 'json' };
console.log(compilerOptions);
尝试在 Node.js 22 中运行:
> node index.js
(node:11064) ExperimentalWarning: Importing JSON modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
file:///C:/Users/matt.mower/source/with-json-tsc/index.js:1
import { compilerOptions } from './tsconfig.json' with { type: 'json' };
^^^^^^^^^^^^^^^
SyntaxError: The requested module './tsconfig.json' does not provide an export named 'compilerOptions'
at ModuleJob._instantiate (node:internal/modules/esm/module_job:171:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:254:5)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:482:26)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)
Node.js v22.6.0
尝试在 Chrome 127.0.6533.120 (
<script async type="module" src="./index.js"></script>
) 中运行:
Uncaught SyntaxError: The requested module './tsconfig.json' does not provide an export named 'compilerOptions' (at index.js:1:10)
如果我将命名导入替换为以下内容,
index.js
在 Node.js 22 和 Chrome 127 中都可以正常运行:
import tsconfig from './tsconfig.json' with { type: 'json' };
console.log(tsconfig.compilerOptions);
微软在 TypeScript 5.7(尚未发布)中修复了这个问题。使用导入属性导入 JSON 时,将不允许命名导入。
拉取请求:验证 JSON 导入到
--module nodenext
中的 ESM
描述片段:
中 JSON 文件导入的命名导入出现错误,因为这些在 Node.js 中不起作用。--module nodenext