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:
JavaScript
x
5
1
my-module
2
--src
3
----index.js
4
----something-else.js
5
package.json
:
JavaScript
1
5
1
{
2
"name": "my-module",
3
"root": "src/index.js"
4
}
5
Implementation:
JavaScript
1
3
1
import myModule from 'my-module';
2
import somethingElse from 'my-module/src/something-else';
3
(or using require
)
JavaScript
1
3
1
var myModule = require('my-module');
2
var somethingElse = require('my-module/src/something-else');
3
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.