0

在您阅读下面的冒险之前,我正在寻找一种在模块中加载 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/ programen/fetch/package.json' 包含“类型”:“模块”。要将其视为 CommonJS 脚本,请将其重命名为使用“.cjs”文件扩展名。

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

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 文件并按照这里的建议重新启动视觉代码工作室。
然后我再次运行脚本

node index.js

然后我得到这个错误

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

我通过运行这篇文章的提示来解决这个问题

node --experimental-json-modules

现在它可以工作了!

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

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

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

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

"compilerOptions": {
    "resolveJsonModule": true,
4

1 回答 1

2

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

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

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

import credentials from "./credentials/sheets123456123456.json";

console.log(credentials);
于 2021-09-01T14:00:35.433 回答