Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a Module and Library in JavaScript

I am learning ES6 modules. But I am confused with what's the difference between a module and library.

And also how module and library is different than a node.js package.

like image 352
Narayan Prusty Avatar asked Jul 10 '15 11:07

Narayan Prusty


1 Answers

A module is a unit of software. This refers - depending on the context - to a self-contained part of source code, to the file that the former is found in, or to the module object (data structure) said code declares (or generates when executed).
Typically there's a 1:1:1 relation between these, and this is a good practise. You seldomly find multiple modules in the same source file1. ES6 implementations will enforce this by taking single files as single modules, that can be imported by their unique name - just as it previously worked with CommonJS or AMD modules.
Next to ES6 modules, there also has been the module pattern, which uses IIFEs to encapsulate code and create singleton objects. See What is this JavaScript pattern called and why is it used?, here or the JS design patterns book for details.
And since modularity is so important, there have been many approaches at implementing module loaders, each with its own syntax and subtleties, often being part of a larger framework. See this article for further discussion.

A library is a collection of useful things that belong together and are distributed as a whole. This might comprise more than pure source code or more than a single language, but typically is not when we talk of a "javascript library". A library, consisting of a set of js functions, typically exports them as a module.

1: Except when they've been minified to a single script. Also, HTML5 might introduce ways to declare inline ES6 modules.

like image 73
Bergi Avatar answered Oct 15 '22 07:10

Bergi