0

I am trying import a JSON file into a TypeScript script using await import(filepath) but am receiving the following error running script with npx ts-node <script>:

"CustomError: ERR_UNKNOWN_FILE_EXTENSION .json /path/to/file.json"

This is the code I use to import the file:

const serAcc: ServiceAccount = await import(GOOGLE_APPLICATION_CREDENTIALS, {assert: { type: "json" });

where GOOGLE_APPLICATION_CREDENTIALS is a string.

These release notes have some information about adding an assert property to dynamic imports.

The following is my tsconfig.json:

{
    "compilerOptions": {
        "target": "es2017",
        "useDefineForClassFields": true,
        "module": "ESNext",
        "lib": ["ESNext", "DOM"],
        "moduleResolution": "Node",
        "strict": true,
        "sourceMap": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "esModuleInterop": true,
        "noEmit": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noImplicitReturns": true,
        "skipLibCheck": true
    },
    "ts-node": {
        "esm": true
    },
    "include": ["src", "utility/test.ts", "utility/tests", "organize.js", "index.ts"]
}

This is my directory structure:

- tsconfig.json
- utility:
  - storageScripts:
    - uploadFile.ts

I am calling the file from the root directory with:

npx ts-node ./utility/storageScripts/uploadFile.ts

Is there something wrong with my tsconfig.json that is causing improper module resolution? I set my module Resolution to "Node", and resolveJsonModule and isolatedModule to true which I have seen helped others with similar issues.

I have also had issues with importing .ts files as well when running scripts with npx ts-node, but if I specify that the files are .ts files, there is no error:

// @ts-ignore
import { object } from "file.ts"

How can I import .json files to a TypeScript script using ts-node

Thanks

Matthew Keller
  • 283
  • 2
  • 8
  • Do [these answers](https://stackoverflow.com/questions/60205891/import-json-extension-in-es6-node-js-throws-an-error) answer your question? – Alex Wayne Jun 23 '22 at 00:20
  • @AlexWayne I saw that discussion, but using that tag with ts-node does not work. I also added an assert property to my import function parameters (updated in my question) that still causes the same error. – Matthew Keller Jun 23 '22 at 13:17
  • Hey Matthew, I have the same problem.. did you manage to find a solution to this issue? Thanks ! – caha11 Jul 11 '22 at 04:27
  • I wasn't able to use the `import` keyword, but for now I have been using fs.readFileSync() from the `fs` module – Matthew Keller Jul 11 '22 at 14:10
  • Eg: jsonObject = `JSON.parse(fs.readFileSync("path/to/file.json"))` – Matthew Keller Jul 11 '22 at 14:11

0 Answers0