This lesson is picked from Next.js source code. In this article, you will learn how deep the imports are nested for a simple hasBasepath utility function.
hasBasepath
This above code snippet is from next/src/client/index.ts. hasBasePath is imported from base-path.ts
This is level 1. I usually take it 2 levels but never beyond. I resort to put the functions in the same file that are in the “proximity”. all hasBasePath does is call pathHasPrefix
pathHasPrefix is imported from path-has-prefix.
This is level 2 in the nested imports. Again, I would have just the put the parsePath in this path-has-prefix file as it is in “proximity”.
parsePath is imported from parse-path.ts
This is level 3. Phewww! I never took it this far, but at this level, I realised, the imports are from shared folder that are used in client and server. If you strictly follow SRP (single responsibility principle) for your functions and files, you can reuse these functions across your codebase as these do not contain side-effects.
Conclusion:
hasBasePath, a simple utility function comes from 3 nested imports in Next.js source code. I stop at second level of nested imports and put the functions in the “proximity”. If you strictly follow SRP (single responsibility principle) for your functions and files, you can reuse these functions across your codebase as these do not contain side-effects.
Get free courses inspired by the best practices used in open source.
About me:
Website: https://ramunarasinga.com/
Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/
Github: https://github.com/Ramu-Narasinga
Email: ramu.narasinga@gmail.com
Top comments (0)