deno 将 JSON 文件作为模块导入

Jan*_*nkt 11 json module deno

我有一个导入 json 的简单文件:

主文件

import json from './file.json'
Run Code Online (Sandbox Code Playgroud)

但是 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)
Run Code Online (Sandbox Code Playgroud)

文件路径正确且文件是有效的 JSON。默认情况下Typescript 编译器应该允许这样做

我还尝试明确启用resolveJsonModule

配置文件

{
  "compilerOptions": {
    "resolveJsonModule": true
  },
  "include": [
    "**/*"
  ]
}
Run Code Online (Sandbox Code Playgroud)

并使用配置运行它,但仍然出现相同的错误:

$ 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)
Run Code Online (Sandbox Code Playgroud)

这里有什么问题?

小智 24

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

import data from "./file.json" assert { type: "json" };
console.log(data);
Run Code Online (Sandbox Code Playgroud)

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


小智 20

根据以下线程,在发布 deno 1.0 之前删除了对读取 json 文件的支持

https://github.com/denoland/deno/issues/5633

但是,您可以使用以下语法来读取 json 文件

Deno.readTextFile('./file.json').then(data => {
    console.log(JSON.parse(data))
})
Run Code Online (Sandbox Code Playgroud)

或者

const data = JSON.parse(Deno.readTextFileSync('./file.json'));
Run Code Online (Sandbox Code Playgroud)

另外,请务必使用--allow-read标志运行包含上述代码的文件。否则你会得到一个权限被拒绝的错误

deno run --allow-read index.ts
Run Code Online (Sandbox Code Playgroud)


Mar*_*nde 14

作为 Afeef 答案的替代方案,由于JSON文件是有效的对象文字,您可以export default向其中添加并将扩展名更改为.js.

来自settings.json

{
   "something": {
      "foo": "bar"
   } 
}
Run Code Online (Sandbox Code Playgroud)

settings.js

export default {
   "something": {
      "foo": "bar"
   } 
}
Run Code Online (Sandbox Code Playgroud)

现在你可以使用 import

{
   "something": {
      "foo": "bar"
   } 
}
Run Code Online (Sandbox Code Playgroud)

除了较短之外,好处是您不需要--allow-read访问