Skip to content

Modules in native JavaScript, compared to CommonJS

Go ahead and check out jsmodules.io for a quick overview of how modules will work in JS when they’re available (assuming ES6).

Looking at the side-by-side comparison of JS modules and CommonJS, the first thought I have is that this form reminds me of Python (import foo from bar). At the simplest level:

CommonJS:

var foo = require('foo');

Modules

import foo from "foo";

I see the benefits of both, but believe I’ll be an enthusiastic adopter of the new syntax when available. In CommonJS’s favor, it works very well the way JavaScript works right now – building objects with property/value pairs (those values can be functions/methods, etc). However, I like the power of being able to import a function from a package, and would be curious as to how that works in the internals (do you reduce the “cost” of loading that module then?).

import { someFunction } from "package";
someFunction('hi');

Definitely very interesting. Thoughts? Love it? Hate it?

And if you want to use it today, it looks as though the Traceur compiler has it.

 

One Reply to “Modules in native JavaScript, compared to CommonJS”

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.