Sebastian De Deyne Sebastian De Deyne - 6 months ago 11
Node.js Question

Is it possible to set the root directory of a node module?

If I publish a node module with source files in a

src
directory, and people would like to import a file in their project, they would need to specify the full path from the module.

Example:

Structure:

my-module
--src
----index.js
----something-else.js


package.json
:

{
"name": "my-module",
"root": "src/index.js"
}


Implementation:

import myModule from 'my-module';
import somethingElse from 'my-module/src/something-else';


(or using
require
)

var myModule = require('my-module');
var somethingElse = require('my-module/src/something-else');


Is there any way to set up the package so that it knows
src
is my sources root, allowing users to require
somethingElse
with
my-module/something-else
?

If this isn't possible, would it be a good/bad idea to pull the files out of
src
on prepublish?

Answer

From my experience, what is typically done in this instance is either:

  1. Have a something-else.js file in the root which contains only require('src/something-else'); Users can then just require('my-module/something-else'); In this case you have a nicer API which means any changes to your directory structure in future wouldn't break your users code. i.e. you might move something-else to my-module/other-sources/something-else and you need only change the root file and your users code will still work.
  2. You create a core my-module which requires everything that your module has available and users can then choose which part of the module via myModule.somethingElse

Otherwise, I haven't come across a method to set the sources root explicitly. That option could be handy though if it does exist.

Comments