I’m fairly new to node.js/express and I really like it so far.
I use ES6 Syntax for imports.
When i started my project, i created all my routes like this :
app.get("/getmenu", (req, res) => {
import("./js/get/getmenu.js").then((result) => {
result.getMenus(req).then((menu) => {
res.json(menu);
})
});
});
With all the logic and database call in the getMenu() function (store in getmenu.js file).
It works well, however, now that I understand better how things work, i start asking myself if dynamic import are any useful in this case? In node in general?
Wouldn’t it be easier to maintain and more performant to go with something like this :
import {getMenuRoute} from "./routes/getmenuroute.js";
...
app.get("/getmenu", getMenuRoute);
With all the logic and database call in the getMenuRoute() function in the dedicated file.
As far as i understand, import are only made once anyway. By doing them dynamic, I only speed up the server starting? But delay the first request to this route? Imported functions are stored somewhere in memory, do I avoid a global variable creation with my dynamic route? Does it matter?
2
Answers
That’s a matter of opinion, but in the given example, I suspect most people would agree that no, the dynamic
import
doesn’t do anything useful for you there (but keep reading, depends how many routes you have).Right.
Right. When you import a module, the module’s top-level code is executed. If you have enough of them, that can delay server startup, in two ways:
No, there’s no global variable creation in either case. Top-level identifiers in modules are not globals.
It’s definitely useful in general:
If you have hundreds or even thousands of routes, dynamically importing them on first use can reduce server startup time (as you said).
If you need to pick among different imports on the basis of the environment (development vs. staging vs. production, other characteristics of the environment), dynamic import is useful for only importing the code you’re actually going to run, and not the code for other environments.
Well, as per your question title, dynamic import is useful in Node.js in some scenarios, such as conditional loading and lazy loading.
Thanks