Diego Martín Nieto Cid

Project and application `node_modules`

An *application* node_modules directory may be used to effectively remove relative paths in source files when referencing to the application sub-modules.

The node_modules folder contains, most of the time, the project dependencies that it needs to work. The src folder is then used to hold the source code of the application which oftentimes is compiled down to a compatible ECMAScript version into dist or build folders.

When the source folder contains the sub-modules of the application, references to them start to spring in the form of relative paths with a series of .. before the actual module. This relative paths become unmanageable rather quickly as they are not tolerant to directory restructuring.

To solve this problem some bundlers support the concept of aliases which allow a symbol to be used as a kind of absolute reference relative to the configured base directory. Another strategy is to define NODE_PATH to be the project's src directory.

The strategy explored in this article takes advantage of the way modules are resolved by nodejs, that is check the path to the current directory in reverse order.

By creating a node_modules directory inside the project's src other files may use the sub-modules without any prefix, just as project dependencies are referenced. In essence, an application node_modules folder.

Let's review how the directory structure of such a project could look like:

  project-root
  ├── node_modules
  ├── package.json
  └── src
      ├── node_modules
      │    └── project-name
      │        ├── module-a
      │        └── module-b
      └── index.js

The project-name folder creates a namespace of modules that helps avoiding conflicts with released packages which would be installed inside the node_modules under project-root.

With this project setup index.js or other files under the src folder may reference sub-modules in a very natural way:

const a = require('project-name/module-a')

Copyright 2024 - Diego Martín Nieto Cid