Home » Javascript » Root directory in package.json

Root directory in package.json

Posted by: admin February 12, 2018 Leave a comment


My question concerns an existing library that I wish to publish as an NPM module. The library is already in use, and currently required via the local file system.

How can I specify the root directory of my module’s files?

If I have a structure like:

├── package.json
├── src
|   ├── js
|   └────── lib
|   └───────── my
|   └───────────── thing.js
|   └───────────── that.js

How do I specify that the root of my module, and accessible files is src/js/lib/my/?

I would like to use as follows from an outside project:

var thing = require('my/thing'),
    that = require('my/that');

I saw the "files" property in package.json, is this the right way to go?


As the doc says:

The main field is a module ID that is the primary entry point to your program.

So you’ll have something like "main": "src/js/lib/my/app.js" in your package.json file.

I would suggest you to create an app.js file and module.exports your different children. For example:

 module.exports.thing = require('./thing');
 module.exports.that = require('./that');

And use them like this:

var mylib = require('mylib')
  , thing = mylib.thing
  , that = mylib.that;


package.json is mainly a file used by npm to install and manage dependencies.

the require construct does not care a lot about package.json so you will not be able to use it to subvert the way require works and make it believe that packages are not where the require loading scheme expects them.

See the documentation on https://nodejs.org/api/modules.html and the loading scheme here: https://nodejs.org/api/modules.html#modules_all_together

you could maybe use the technique that the documentation calls ‘Loading from the global folders’ and define the NODE_PATH environment variable.

but I advise you to stick to a more standard way :
– put your modules in a node_modules directory
– or start your module hierarchy in the same directory where your app.js or index.js is located


In webpack, you can specify resolve.alias like this:

  resolve: {
    alias: {
      'my': 'my/src'

or you can specify directions option in package.json

  directions: {
    'lib': 'src/lib'