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?
From my experience, what is typically done in this instance is either:
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. ie 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.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.
Install the module-alias package:
npm i --save module-alias
Add paths to your package.json
like this:
{ "_moduleAliases": { "@lib": "app/lib", "@models": "app/models" } }
In your entry-point file, before any require()
calls:
require('module-alias/register')
You can now require files like this:
const Article = require('@models/article');
Reference :: https://gist.github.com/branneman/8048520
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.