Before you read my adventure below, i'm looking for a simple way to load json credentials in a module. My adventure took many steps, so I assume there is a quicker way!
I try to import modules and load a json. I started with a require:
import { default as fetch } from 'node-fetch';
import { GoogleSpreadsheet } from 'google-spreadsheet';
let creds = require('./credentials/sheets123456123456.json');
I get this error
ReferenceError: require is not defined in ES module scope, you can use import instead This file is being treated as an ES module because it has a '.js' file extension and '/Users/wimdenherder/Documents/Programmeren/Nodejs/Sellvation/programmeren/fetch/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
I tried to rewrite to imports proposed by Stefan Judis in this 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');
But then tslint gives an error:
The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'.ts(1343)
I have to updates tsconfig.json
"compilerOptions": {
"target": "es5",
"module": "esnext"
but the folder does not have a tsconfig.json, so i run
tsc --init
but ironically tslint gives an error in the tsconfig.json file!
No inputs were found in config file
so i create an empty .ts file and restart visual code studio as suggested here.
Then i run again the script
node index.js
Then i get this error
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for /Users/wimdenherder/Documents/Programmeren/Nodejs/Sellvation/programmeren/fetch/credentials/sheets123456123456.json
which i fix by running the hint from this post
node --experimental-json-modules
and now it works!
So my question is, is there an easier way to load json in modules in nodejs?
PS: i also got this typescript error
Cannot find module '/credentials/sheets2569224e80ce5d0c2d.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.
which i solved by updating tslint.config and restarting visual code
"compilerOptions": {
"resolveJsonModule": true,