Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is CommonJS and why should I care how it can help in writing .js applications? [closed]

I'm learning JS and someone more experienced mentioned that they use CommonJS to handle keeping js code organized (since there's no "module" functionality).

I looked on Quora, but it explained the group and it's goals, not so much how I might use it.

like image 566
Clay Nichols Avatar asked Feb 27 '13 23:02

Clay Nichols


People also ask

What is CommonJS used for?

CommonJS is a module formatting system. It is a standard for structuring and organizing JavaScript code. CJS assists in the server-side development of apps and it's format has heavily influenced NodeJS's module management.

What is CommonJS in NodeJS?

CommonJS is a popular modularization pattern that's used in Node. js. The CommonJS system is centered around a require() function that loads other modules and an exports property that lets modules export publicly accessible methods.

Why does node js use CommonJS?

The CommonJS module specification is the standard used in Node. js for working with modules. Modules are very cool, because they let you encapsulate all sorts of functionality, and expose this functionality to other JavaScript files, as libraries. The CommonJS module specification is the standard used in Node.

What does module CommonJS mean?

When you set "module" to "commonjs" in tsconfig. json, this means that the modules in the compiled .


1 Answers

CommonJS modules enables you to include javascript modules within the current scope and effectively keeps the global scope from being polluted.

This massively reduces the chance of naming collisions and keeps code organised.

That said I think it's pretty safe to say that AMD modules have now become more popular than CommonJS.

The RequireJS website has a very good section on why to use modules and the differences between CommonJS and AMD.

like image 114
RayViljoen Avatar answered Oct 20 '22 20:10

RayViljoen