我试图在nodejs中导入JSON。
// tsconfig.json
...
"lib": ["es2022"],
"target": "es2022",
"module": "nodenext",
"moduleResolution": "node",
...
"resolveJsonModule": true,
...
// .swcrc.json
...
"target": "es2022",
...
"module": {
"type": "nodenext",
...
然后,当我编译它并运行"start": "NODE_ENV=production node --es-module-specifier-resolution=node --experimental-json-modules --no-warnings lib/index.js"
时,就会得到TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "file:///path/to/data.json" needs an import assertion of type "json"
。
我接着补充:
import data from './data.json' assert {type: 'json'}
console.log(data)
然后打开编译后的代码,我可以看到:
import data from"./data.json";console.log(data);
//# sourceMappingURL=index.js.map
此时,我想也许是SWC没有编译断言?
然后我运行tsc --emitDeclarationsOnly
,在这里我得到了Import assertions are not allowed on statements that transpile to commonjs 'require' calls.
,我不知道为什么公共程序和它有任何关系,我在任何地方都不使用commonjs,对吗?
另外,我使用节点18。
我做错了什么?我只是想进口那个json。
编辑:好的,TS中断的原因是因为缺少"include": ["src/**/*.ts", "src/**/*.json", "types.d.ts"],
。在加上它现在起作用之后。不幸的是,SWC仍然给出了相同的错误,所以我无法运行它。
发布于 2022-07-07 20:16:07
终于弄明白了。在.swcrc.json中有一个实验性的选项,允许您告诉它保留断言。
// .swcrc.json
...
"jsc": {
"experimental": {
"keepImportAssertions": true
}
}
https://stackoverflow.com/questions/72903040
复制相似问题