Skip to content

Instantly share code, notes, and snippets.

@subzey
Last active November 12, 2015 19:09
Show Gist options
  • Select an option

  • Save subzey/a98ad138b0e41b09eee3 to your computer and use it in GitHub Desktop.

Select an option

Save subzey/a98ad138b0e41b09eee3 to your computer and use it in GitHub Desktop.
Sample library code organization

Sample library code organization

Did you know you can require specific files from a module?

Imagine we have an library like underscore: a set of different functions that mostly don't depend on each other. We have a unicorn function and a rainbow function that depends on unicorn.

We create the following directory structure:

+ (Project root)
|
+- package.json
|
+- main.js
|
+- unicorn.js
|
+- rainbow.json

After npm install the unicorn functionality can be obtained via require('wonderland/unicorn'). And the rainbow function can be obtained using require('wonderland/rainbow').

Looks weird, but there are certain benefits.

Why can't we just stuff it into one JS file?

We can, for sure, but what if a user don't need rainbows? Rainbow making code would be included and bundled anyway, despite the fact it's unused.

Why can't we keep it in separate modules?

With separate GitHub projects? Are you serious?

Moreover, if there would be a sparkles module that also depends on unicorn, then unicorn would be npm-installed twice. Not a good option.

So… that's it. If you're going to create an utility belt that provides several almost not related functions, please, let user decide what to include.

// Nothing.
{
"private": true,
"name": "wonderland",
"main": "main.js"
}
module.exports = function rainbow() {
var unicorn = require('./unicorn');
return 'A rainbow and ' + unicorn();
};
module.exports = function unicorn(){
return "a unicorn!";
};
@sapegin

sapegin commented Nov 12, 2015

Copy link
Copy Markdown

Another solution: single GitHub project but many npm packages. Example: Babel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment