I'm currently trying to build a simple Typescript project that calls from a JSON file. I'm trying to import it like this in my index.ts file.
import fs from 'fs';
const filePath: string = 'src/coffee.json';
fs.readFile(filePath, 'utf8', (err: Error, data) => {
if (err) {
console.error('Error reading JSON file:', err);
return;
}
try {
const jsonData = JSON.parse(data);
console.log(jsonData);
} catch (parseError) {
console.error('Error parsing JSON:', parseError);
}
});
However, after running npm start, I get this error in the console.
Uncaught TypeError: Failed to resolve module specifier "fs". Relative references must start with either "/", "./", or "../".
I tried changing the import statement to
var fs = require('fs');, but I got this error instead
Uncaught ReferenceError: require is not defined at index.js:2:10
My tsconfig.json file is as follows:
{
"include": ["src", "types"],
"compilerOptions": {
"module": "esnext",
"target": "esnext",
"moduleResolution": "node",
"jsx": "preserve",
"baseUrl": "./",
/* paths - import rewriting/resolving */
"paths": {
// If you configured any Snowpack aliases, add them here.
// Add this line to get types for streaming imports (packageOptions.source="remote"):
// "*": [".snowpack/types/*"]
// More info: https://www.snowpack.dev/guides/streaming-imports
},
"allowSyntheticDefaultImports": true,
/* more strict checking for errors that per-file transpilers like `esbuild` would crash */
"isolatedModules": true,
/* noEmit - We only use TypeScript for type checking. */
"noEmit": true,
/* Additional Options */
"strict": false,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"useDefineForClassFields": true
}
}
My project structure can be found here: https://i.stack.imgur.com/rbogI.png
This error basically breaks all the rest of the Typescript and causes the app to become nonfunctional. I've already tried restarting TS server and no dice. Any help would be greatly appreciated.