2

I have a javascript project which is used as a utility in another project and I want to package it using npm so that more projects can use it. The project structure I created is:

Project/
|-- src/
|   |-- main.js
|   |-- index.js
|
|   |-- extensions/
|   |   |-- core-1.js
|   |   |-- ...
|   |   |-- core-n.js
|   |   |-- other-1.js
|   |   |-- ...
|   |   |-- other-n.js
|   |

The main file creates an object with some utility functions in it which is used by the extensions. The index.js file takes all the objects and functions from extensions and main and put it into a single namespace to export it. What I want is when anyone install this node module they should be able to use the utilities in the main file and core extensions. If they want to use other extensions they should have the ability to explicitly require the other extensions. Is it good idea to create separate node projects for other extensions which has dependency one the main project? or is there any other way provided by npm or node to achieve this?

1 Answer 1

1

When you do require("<your-module>"), node.js loads a file mentioned in main property inside your package.json or index.js by default. There is a way to load individual files from a particular package. Just append your file path after your module name prepended with slash.

In your example extensions can be individually loaded like this

var u1 = require("Project/src/extensions/other-1");
var u2 = require("Project/src/extensions/other-2");

Only other-1 and other-2 extensions will be loaded in variables u1 and u2 respectively.

You should ensure that appropriate files are loaded in index.js and main.js.

Here is an example node module https://github.com/juzerali/require-demo

You should try installing project as a node module and try playing with it to understand how it works.

1
  • 1
    Thanks, I tried this approach and it worked well for me. Just a note my extensions depends on the core, so I had to require the core inside the extension file. Commented Oct 4, 2016 at 16:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.