goldbergyoni / nodebestpractices

:white_check_mark: The Node.js best practices list (July 2024)
https://twitter.com/nodepractices/
Creative Commons Attribution Share Alike 4.0 International
99.36k stars 10.11k forks source link

"Require modules first, not inside functions" #1182

Open avin-kavish opened 2 years ago

avin-kavish commented 2 years ago

"Require modules first, not inside functions"

This causes the module to be loaded optimistically when the scripts are loaded, which increases the boot time of the app. In cases where boot time is important, this is not desirable behaviour. Regarding the point about this catching errors early, having a comprehensive test suite will help catch errors due to missing deps in functions.

josh-hemphill commented 2 years ago

When implementing async imports in large project, you also run into lots of issues. I've done a lot of web servers where auto-imports resolve with dynamic imports out of necessity, and while it may "start" right away, you have no guarantees about what has loaded and is functional. Maybe some updates to that section is warranted, but another huge problem with "require" inside functions is if you ever want to convert to ESM syntax, you'll have to convert a lot of stuff to async/await. Personally I also prefer to bundle and pre-optimize my server projects when possible, and lazy-loading or dynamic imports usually either entirely prevent or cripple the ability to do that.