Can Node.js use a different filename for the directory index file than `index.js`?

When we write require('some/directory')

.

It will search some/directory/index.js

if some/directory

is a directory.

But what if I want to use a different filename, for example _index.js

? (Thus, it can be sorted in its children in the tree.)

+3


source to share


3 answers


The default filename is index.js, but you can use a different file via package.json.

In this file, you must have a key name :

  "main": "index",

      



replace whatever name you prefer, even in a different directory:

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

      

see https://docs.npmjs.com/files/package.json

+2


source


It's impossible.

The default filename is hardcoded and should be index.js

or index.node

according to this:



https://nodejs.org/api/modules.html#modules_folders_as_modules

0


source


It is hardcoded inside the node core, you can see it in action here: https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/loader.js#L224

As the documentation says, first it tries to get the package from node_modules, if there is no such package, it tries to get it from index.js from this folder, and as a last resort it tries to open the specified (if any) .json package in that folder. If nothing was found, it gives an error with a message about the absence of such a module

0


source







All Articles