javascript / intermediate
Snippet
Conditional Module Loading
Dynamic imports allow you to load modules asynchronously and conditionally at runtime. This is useful for loading large dependencies only when needed, reducing the initial memory footprint of your Node.js application.
snippet.js
1
2
3
4
5
const mode = process.env.NODE_ENV;if (mode === 'development') {const logger = await import('./dev-logger.js');logger.init();}
nodejs
Breakdown
1
const logger = await import('./dev-logger.js');
Asynchronously loads the module using the dynamic import() function.
2
logger.init();
Calls the exported init function from the dynamically loaded module.