I have a pretty standard node module using babel to transpile our code which is then output to a 'lib' folder. the package.json points 'main' to 'lib/index.js' so that people can just require('my-module')
However, if I have a subdirectory (say my-module/server for example) then when they use my-module they have to do require('my-module/lib/server')
. I've seen people put post build steps that will copy package.json into lib, but that just feels hacky and wrong to me. Is there any way in npm to specify a main directory whereby any require()'s of my module would start at that directory? Then I can just have users do require('my-module/server') without the lib part...
At runtime node creates a registry of the full paths of all loaded files. The modules are loaded first, and thus at the top of this registry. By selecting the first element of the registry and returning the path before the 'node_modules' directory we are able to determine the root of the application.
Node Modules Packages are dropped into the node_modules folder under the prefix . When installing locally, this means that you can require("packagename") to load its main module, or require("packagename/lib/path/to/sub/module") to load other modules. Global installs on Unix systems go to {prefix}/lib/node_modules .
In order to get the root directory path, you can use _DIR_ or dirname(). echo dirname(__FILE__); Both the above syntaxes will return the same result.
dirname() to get the path of root project structure. Use os. path. dirname(path) where path is the path to any file in the top level of the project.
I think the best solution is that you have as main an index.js and on it all the submodules so you can do did something like require('your-module').server
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With