我有一个导入json的简单文件:
main.ts
import json from './file.json'但是,deno在导入json文件时引发以下错误:
$ deno run main.ts
Compile file:///home/path/to/project/main.ts
error: Uncaught TypeError: Cannot resolve extension for "file:///home/path/file.json" with mediaType "Json".
at getExtension ($deno$/compiler.ts:218:13)
at new SourceFile ($deno$/compiler.ts:263:22)
at Function.addToCache ($deno$/compiler.ts:339:16)
at processImports ($deno$/compiler.ts:743:31)
at async processImports ($deno$/compiler.ts:753:7)
at async compile ($deno$/compiler.ts:1316:31)
at async tsCompilerOnMessage ($deno$/compiler.ts:1548:22)
at async workerMessageRecvCallback ($deno$/runtime_worker.ts:74:9)文件路径正确,文件是有效的JSON。默认情况下,类型记录编译器应该允许这样做。。
我还试图显式地启用resolveJsonModule
tsconfig.json
{
"compilerOptions": {
"resolveJsonModule": true
},
"include": [
"**/*"
]
}并使用配置运行它,但仍然得到相同的错误:
$ deno run main.ts --config=tsconfig.json
Compile file:///home/path/to/project/main.ts
error: Uncaught TypeError: Cannot resolve extension for "file:///home/path/file.json" with mediaType "Json".
at getExtension ($deno$/compiler.ts:218:13)
at new SourceFile ($deno$/compiler.ts:263:22)
at Function.addToCache ($deno$/compiler.ts:339:16)
at processImports ($deno$/compiler.ts:743:31)
at async processImports ($deno$/compiler.ts:753:7)
at async compile ($deno$/compiler.ts:1316:31)
at async tsCompilerOnMessage ($deno$/compiler.ts:1548:22)
at async workerMessageRecvCallback ($deno$/runtime_worker.ts:74:9)这里怎么了?
发布于 2022-01-12 13:15:07
因为Deno1.17现在可以在ESM中再次导入JSON。现在必须使用导入断言:
import data from "./file.json" assert { type: "json" };
console.log(data);有关更多信息,请参见https://examples.deno.land/importing-json。
发布于 2020-05-20 07:51:41
如下所示,在发布Deno1.0之前,删除了对读取json文件的线程支持
https://github.com/denoland/deno/issues/5633
但是,可以使用以下语法读取json文件
Deno.readTextFile('./file.json').then(data => {
console.log(JSON.parse(data))
})或
const data = JSON.parse(Deno.readTextFileSync('./file.json'));此外,请确保使用--allow-read标志运行包含上述代码的文件。否则,您将收到拒绝权限的错误。
deno run --allow-read index.ts发布于 2020-05-20 12:33:02
作为Afeef答案的另一种选择,由于JSON文件是一个有效的对象文本,您可以将export default添加到其中并将扩展名更改为.js。
来自settings.json
{
"something": {
"foo": "bar"
}
}致settings.js
export default {
"something": {
"foo": "bar"
}
}现在你可以使用import了
import settings from './settings.js'
console.log(typeof settings) // object
constole.log(settings.something.foo) // bar好处是,除了更短的时间之外,您不需要--allow-read访问
https://stackoverflow.com/questions/61907155
复制相似问题