dynamic import 1) 2) 3) 4) is in stage 4. is when the import statement is used as a function in order to execute it at runtime.
The import() function-like form takes the module name as an argument and returns a Promise which always resolves to the namespace object of the module.
The import function:
import('https://cdn.jsdelivr.net/npm/[email protected]/dist/moment.js').then( ({ default: moment}) => {
const now = moment().format();
console.log(`The actual time is "${now}"`);
});
The import above expect the module to export a property named 'default'. ie at the end of the file, you could see something like that
export { Moment as default };
If this is not the case in your module, you may get this error:
The requested module 'xxxx' does not provide an export named 'default'
JSON module 5) can also be imported dynamically.
If you want to load JSON file has object on node, you can just read it and parse it such as:
const dataObject = JSON.parse(fs.readFileSync('data/file.json'));
Example with:
{
"prop": {
"id": 1,
"name": "Nico"
}
}
file = 'data.json'
const data = await import(file).then(module => module.default);
file = 'data'+'1.json'
const data = import(file).then( ( { prop: data} ) => data);
const examData = (
(
await import('../../data/exam'+id+'.json')
.then(module => module.default)
)
as unknown as ExamSchema
);