-1

I have had a stupid question on my mind for a while: How does require("moduleName") work?

I understand that if I have a file moduleA.js in my project, I could load the module using require("./moduleA"). But for many "well-known libraries" such as express, lodash, etc, I don't need to explicitly write the relative path in which the is library located. Instead I just use the module name (e.g. require('lodash');). My question is: how does that work? How can I make my own module work in that way, where the module can be loaded globally without writing the path(e.g. require('moduleA')).

Thanks

Matt Morgan
  • 4,900
  • 4
  • 21
  • 30
AlexLuo
  • 458
  • 1
  • 4
  • 12
  • See https://gist.github.com/mathisonian/c325dbe02ea4d6880c4e, https://github.com/feross/buffer – guest271314 Jan 12 '18 at 19:53
  • 1
    This is a pretty loaded question, RisingStack Engineer has a [good blog post on this](https://blog.risingstack.com/node-js-at-scale-module-system-commonjs-require/) that has a good amount of detail on how the Module System in Node (CommonJS) works. – peteb Jan 12 '18 at 19:57

2 Answers2

1

When you install a library with NPM, the library get installed in a folder called node_modules and when you make the require keyword, node look for the package name in that folder. When you require for a js file, you should specify its path.

zb22
  • 3,126
  • 3
  • 19
  • 34
1

A relative path like require('./moduleA') means you're importing a script or module within your project. A "well-known" path like require('loadash') means you're importing an external dependency, which may be installed locally to your project under C:/path/to/project/node_modules/lodash or globally to your account or computer, depending on how you configured npm when you installed Node.js. That path may be something like C:/Users/yourname/AppData/Roaming/npm/node_modules/lodash for example.

If you publish your module on npm, others will be able to install it as an external dependency and require() it without having to specify a relative path to it.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153