PHP-Like Autoloader using Node.js

Edit December 2020

Yarn2 did release a feature called Plug'n'Play which seems to mimic PHP's autoloader: https://yarnpkg.com/features/pnp

It is known to have issues with some packages but I have not tested it myself.


The short answer is: No

For more details, continue reading:

There are two major challenges around the current way require or import currently work:

  1. Relative paths are hard to read and can become confusing when using files with the same name.
  2. Developers must heavily rely on IDEs to refactor their code or to find where a file is when inside another file.

While PHP seems to have developed its own standard and is a bit in its own league, even if someone would develop an equivalent solution to achieve the same for Node.js/JavaScript, we would still need good IDE support. To get good IDE support, this type of change would either:

  1. Need to be transparent and integrate to the way IDEs currently work.
  2. Be a change that is driven by the community itself (either require or import changes that can support absolute paths)

There are several answers here (https://gist.github.com/branneman/8048520) and they all seem to break IDE support (I only tested with WebStorm):

  1. Using aliases or prepending the path with variables: Breaks IDE support for autocomplete and renaming/refactoring.
  2. Using NODE_PATH as root path: Breaks IDE support for autocomplete and renaming/refactoring.
  3. Wrapping require to support /: Breaks IDE support when renaming/refactoring.
  4. Creating a new custom method: Breaks IDE support for autocomplete.

Overall, given that IDE support take precedence over code readability, it looks like there is no good way to implement changes to the current dependency management using Node.js without having the community behind such change.


While not exactly like PHP, it is similar and very handy. I like this package. It is a bit older, but definitely in the right direction.

https://github.com/Specla/Autoloader

Then for database models if you are using Sequelize like I am it is pretty good. https://github.com/boxsnake/sequelize-autoload