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?
Advertisement
Answer
From my experience, what is typically done in this instance is either:
- Have a
something-else.js
file in the root which contains onlyrequire('src/something-else');
Users can then justrequire('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 movesomething-else
tomy-module/other-sources/something-else
and you need only change the root file and your users code will still work. - You create a core
my-module
which requires everything that your module has available and users can then choose which part of the module viamyModule.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.