About
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.
Example
How to import an ES module
The import function:
- fetches and executes an es module
- returns a promise that resolves into a module object that contains all its exports.
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'
How to import Json data
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:
- The whole Json file
{
"prop": {
"id": 1,
"name": "Nico"
}
}
- Return the whole object
file = 'data.json'
const data = await import(file).then(module => module.default);
- Return only a sub-part
file = 'data'+'1.json'
const data = import(file).then( ( { prop: data} ) => data);
- Typescript. If the import is really dynamic, typescript will complain and you need to assert the type
const examData = (
(
await import('../../data/exam'+id+'.json')
.then(module => module.default)
)
as unknown as ExamSchema
);