How to code like playing LEGO™

Modularity is a big trend and I'm not the first to hop on this train. Today, I'm going to show you how easy you can build a multi-module app with vanilla Javascript and some awesome tools.

Recipe

Ingredients

First of all, I'm going to assume you know a few things beforehand :

Object Oriented Programming

How to write JS

Basics of NPM

Steps

The ground

Lets start with an empty directory for your project (we'll name it unicorn) and initialize it

npm init

and create the main file index.js with an old-school JS class

functionUnicorn(name){this.name=name;}Unicorn.prototype={shine:function(){// All kind of good stuff here 🦄}}vardazzle=newUnicorn("Dazzle");dazzle.shine();

Decoupling

Now image that you want to use the Unicorn class in another project, or just open-source it to the Humanity. You could create another directory with another repo, but let's be smarter. The Unicorn class is so linked to the Unicorn project that we'll use NPM scoped package name for clarity.

Which will have an index.js too with the class inside it. Since we left the plain browser JS with import/export statement, why not use the beautiful ES6 class syntax.

exportdefaultclassUnicorn{constructor(name){this.name=name;}shine(){// All kind of good stuff here 🦄}}

Perfect !

Wrapping

Ok nice one, but now I can't use it in my browser, you dumbo !

First, how are you calling me ?
Then yeah, I know, for now it's all experimental syntax and stuff, but there's tools to handle it for you. I like to use webpack with babel, of course, it's not the only solution.

The whole webpack configuration could fill another article, so I'll just show one that work. Set a new file called webpack.config.js with some instructions inside.

module.exports={entry:"./index.js",// Main file to readmodule:{rules:[{test:/\.js$/,// For all file ending with ".js"use:{loader:"babel-loader",// Use babeloptions:{presets:["babel-preset-env"],},},}],},output:{filename:"dist/unicorn.js",// Output the result in another filelibrary:"Unicorn",// Under "Unicorn" namespacelibraryTarget:"this",libraryExport:"default",},};

Then, if you run npx webpack it will build all your sources into one file usable by plain web browser.

Managing

You can now create lots of sub-modules and wrap them all in one file. You can even have sub-sub-modules and so on. Just put them all in the modules directory.
As your project grows, it'll be harder and harder to manage all this menagerie.

Thanks for your comment. The code is pure ES6 syntax (no post-process, no frame-work). The use of webpack + babel is just there to make it work on browser. It feels vanilla to me. How would you have done ?