TypeScript 5.3 introduced support for import attributes. When building an ESM project, the compiler allows destructuring during import, but I don’t know any javascript runtimes that support this. Should TypeScript be downcompiling or disallowing destructured JSON imports?
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"
}
}
Test building with Node.js 22.6.0 and TypeScript 5.5.4.
Compilation with npx tsc
produces no warnings or errors and outputs index.js
:
import { compilerOptions } from './tsconfig.json' with { type: 'json' };
console.log(compilerOptions);
Attempt to run in 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
Attempt to run in 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)
If I replace the destructured import with the following, index.js
runs fine in both Node.js 22 and Chrome 127:
import tsconfig from './tsconfig.json' with { type: 'json' };
console.log(tsconfig.compilerOptions);