How can I package a node module with additional submodules?

I am writing a javascript library that contains a main module and several optional submodules that extend the main module. My target is a browser (using Browserify) where I expect the user of my module to only want to use some of my optional submodules and not load the client - just like custom assemblies, it works in lodash

.

How I imagine this works:

// Require the core library
var Tasks = require('mymodule');
// We need yaks
require('mymodule/yaks');
// We need razors
require('mymodule/razors');

var tasks = new Tasks();    // Core mymodule functionality
var yak = tasks.find_yak(); // Provided by mymodule/yaks
tasks.shave(yak);           // Provided by mymodule/razors

      

Now imagine the namespace mymodule/*

contains dozens of these submodules. the user of the library mymodule

has to bear the bandwidth cost of the submodules it uses, but there is no need for a standalone build process like lodash

uses: a tool like Browserify solves the dependency graph for us and only includes the required code.

Can I package something with Node / npm? Am I delusional?

Update: The answer here seems to suggest it is possible, but I cannot figure out from the npm documentation how for the actual structure of the files and package.json

.

Let's say that I have these files:

./lib/mymodule.js
./lib/yaks.js
./lib/razors.js
./lib/sharks.js
./lib/jets.js

      

In mine package.json

I will have:

  "main": "./lib/mymodule.js"

      

But how does node know about other files under ./lib/

?

+3


source to share


1 answer


This is easier than it sounds - when you need a package with its name, it gets the "main" file. So it require('mymodule')

returns "./lib/mymodule.js"

(for your main prop.json package). To directly require additional submodules, simply require them via the filepath.

So, to get the submodule yaks: require('mymodule/lib/yaks')

. If you want to do require('mymodule/yaks')

, you either need to change your file structure to match (move yaks.js to the root folder) or do something tricky where yaks.js is in the root and it just does something like: module.exports = require('./lib/yaks');

...



Good luck with this yak lib. Sounds hairy :)

+4


source







All Articles