【问题标题】:Is there an easy way to load json in a node module?有没有一种简单的方法可以在节点模块中加载 json?
【发布时间】:2021-10-31 00:35:15
【问题描述】:

在您阅读下面我的冒险之前,我正在寻找一种在模块中加载 json 凭据的简单方法。我的冒险经历了很多步骤,所以我认为有更快的方法!

我尝试导入模块并加载 json。 我从一个需求开始:

import { default as fetch } from 'node-fetch';
import { GoogleSpreadsheet } from 'google-spreadsheet';
let creds = require('./credentials/sheets123456123456.json');

我收到此错误

ReferenceError: require is not defined in ES module scope, you can use import instead 此文件被视为 ES 模块,因为它 有一个 '.js' 文件扩展名和 '/Users/wimdenherder/Documents/Programmeren/Nodejs/Sellvation/programmeren/fetch/package.json' 包含“类型”:“模块”。要将其视为 CommonJS 脚本,请将其重命名 使用“.cjs”文件扩展名。

我试图重写 Stefan Judis 在 article 中提出的导入

import { default as fetch } from 'node-fetch';
// import { default as creds } from './credentials/sheets2569224e80ce5d0c2d.json';
import { GoogleSpreadsheet } from 'google-spreadsheet';
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const creds = require('./credentials/sheets123456123456.json');

但随后 tslint 报错:

仅当“--module”选项为“es2020”、“esnext”或“system”.ts(1343) 时才允许使用“import.meta”元属性

我必须更新 tsconfig.json

"compilerOptions": {
        "target": "es5",
        "module": "esnext"

但是文件夹没有tsconfig.json,所以我运行

tsc --init

但具有讽刺意味的是 tslint 在 tsconfig.json 文件中给出了错误!

在配置文件中找不到输入

所以我创建了一个空的 .ts 文件并按照建议 here 重新启动 Visual Code Studio。
然后我再次运行脚本

node index.js

然后我得到这个错误

TypeError [ERR_UNKNOWN_FILE_EXTENSION]:未知文件扩展名“.json” 为了 /Users/wimdenherder/Documents/Programmeren/Nodejs/Sellvation/programmeren/fetch/credentials/sheets123456123456.json

我通过运行 post 的提示来解决这个问题

node --experimental-json-modules

现在它可以工作了!

所以我的问题是,在 nodejs 中是否有一种在模块中加载 json 的更简单方法

PS:我也遇到了这个打字错误

找不到模块“/credentials/sheets2569224e80ce5d0c2d.json”。考虑使用“--resolveJsonModule”导入扩展名为“.json”的模块。

我通过更新 tslint.config 并重新启动可视化代码解决了这个问题

"compilerOptions": {
    "resolveJsonModule": true,

【问题讨论】:

    标签: node.js json


    【解决方案1】:

    通过添加以下选项更新您的 tsconfig.json 文件。

    {
      "compilerOptions": {
        "esModuleInterop": true,
        "resolveJsonModule": true
      }
    }
    

    完成上述操作后,您将能够导入 json 文件,如下所示:

    import credentials from "./credentials/sheets123456123456.json";
    
    console.log(credentials);
    

    【讨论】:

    • 看起来不错,你在哪里找到的?您推荐某些书籍,文档吗?为了避免像我上面那样的冒险;)
    • 当我运行 tsc-watch 时,我在创建的 .js 文件中收到此错误:“typeof import(".../build/index")' 类型上不存在属性 '__importDefault'。 ts(2339)。我该如何解决这个问题?
    猜你喜欢
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多