Vitaliy Leonov
Vitaliy Leonov

Reputation: 222

Resolve module custom main file name

Is it possible to define custom main file name?

const awesomeModule = require('src/awesomeModule'); // correct
// or
const someModule = require('src/someModule'); // fail

There is a structure

/src
    /awesomeModule
        - index.js
    /someModule
        - mainFile.js

I want an array of possible names. Like a webpack config https://webpack.js.org/configuration/resolve/#resolve-mainfiles

Upvotes: 0

Views: 387

Answers (2)

Ruan Martinelli
Ruan Martinelli

Reputation: 364

Yes, technically.

According to the documentation you can specify a path to an entry file by adding a "main" property in the package.json file.

So, if you really want to do this, you would have to create a new package.json inside of the someModule folder with these properties:

// src/someModule/package.json
{ 
  "name" : "someModule",
  "main" : "./mainFile.js" 
}

With that, require('src/someModule') will resolve to your mainFile.js.

However, in my opinion, I think the confusion caused by having multiple package.json files is not worth the few extra characters when requiring a module.

Upvotes: 0

user5773927
user5773927

Reputation:

I don't think so. https://nodejs.org/api/modules.html#modules_all_together

You can require the main file directly require('src/someModule/mainFile').

Upvotes: 1

Related Questions