javascriptnode.jsjsonecmascript-6esmodules

How can I dynamically load a JSON file inside an ECMAScript module?


I am doing:

let filePath = '../../data/my-file.json'
import inputArray from filePath assert { type: 'json' }

This is the result I get:

file:///.../script.mjs:5
import inputArray from filePath assert { type: 'json' }
                       ^^^^^^^^

SyntaxError: Unexpected identifier
    at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:483:14)
    at async link (node:internal/modules/esm/module_job:67:21)

It works if I statically import the JSON file:

import inputArray from './my-file.json' assert { type: 'json' }

Is there a way to dynamically import a JSON file inside ECMAScript modules?

Why is this happening?

I am using Node.js version v18.7.0.


Solution

  • Found a way:

    
    let filePath = '../../data/my-file.json'
    
    let arrayImport = await import(filePath, {
      assert: { type: "json" },
    });
    const inputArray = arrayImport.default 
    
    console.log('result': inputArray)
    
    

    More information here: v8 - Dynamic import().