deno 导入 JSON 文件作为模块

deno import JSON file as module

我有一个导入 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。 Typescript compiler should allow this by default

我还尝试显式启用 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)

这是怎么回事?

根据以下线程,在发布 deno 1.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

作为 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 访问权限

自 Deno 1.17 JSON 现在可以再次导入 ESM。现在必须使用导入断言:

import data from "./file.json" assert { type: "json" };
console.log(data);

有关详细信息,请参阅 https://examples.deno.land/importing-json