AJcodez
AJcodez

Reputation: 34214

npm specify where require package-name/module-name points to

Consider the following folder structure:

- lib
  + main.js
  + optional.js
- src
  + main.coffee
  + optional.coffee
+ package.json

I can specify the main file in package.json no problem with:

  "main": "./lib/main",

But when I require('package-name/optional') I want ./lib/optional. How can I specify that / make it work?

Upvotes: 0

Views: 374

Answers (2)

matth
matth

Reputation: 6299

You can specify files/folders under the package name, but as hexacyanide has pointed out, it isn't possible to specify a custom require option for that specific file. For example:

require('package-name/lib/optional')

Upvotes: 0

hexacyanide
hexacyanide

Reputation: 91769

That isn't possible, because module names are resolved as paths for the required script.

The reason you can specify a main option is because package-name resolves to node_modules/package-name (where package.json can be found) whereas package-name/option will resolve to node_modules/package-name/option which is an entirely different path.

If you'd like to see how the module paths are resolved, you can take a look in the Node source here. The order of functions that lead to path resolution looks like this:

Module.prototype.require
Module._load
Module._resolveFilename
Module._resolveLookupPaths

Upvotes: 1

Related Questions