nodebestpractices icon indicating copy to clipboard operation
nodebestpractices copied to clipboard

"Require modules first, not inside functions"

Open avin-kavish opened this issue 3 years ago • 1 comments

"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.

avin-kavish avatar Jun 17 '22 10:06 avin-kavish

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.

josh-hemphill avatar Jun 17 '22 20:06 josh-hemphill