Sebastian De Deyne Sebastian De Deyne - 1 year ago 58
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

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





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


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

(or using

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
is my sources root, allowing users to require

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

Answer Source

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.