Welcome to the 56th Easy JavaScript Tutorial! The last tutorial was just a text tutorial looking at the .filter()
method available to us. I just finished moving and am still settling in but I will be making more Raspberry Pi tutorials soon, including some potential giveaways! Thought I'd take some time to create a quick tutorial introducing JavaScript modules to you.
If you've done work in languages like Python or Java, or even used frameworks like NodeJS or Angular, you'll be familiar with modules. Modules allow you to create components that you can export
and then import
into other parts of your code. This allows you to reuse code throughout your application more easily than using script tags to embed new JavaScript files in your HTML.
I'm only looking to give you a quick intro to JavaScript modules, I do recommend playing around with them as well as recommending reading the official MDN documentation on JavaScript modules here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
JavaScript modules were introduced in ES6 a few years ago but I'll admit that it's something I haven't used enough of lately.
So let's get started!
In the video below, I have 3 JavaScript files. The main file is simply called main.js. I import it into my index.html as follow:
<script src="main.js" type="module"></script>
As you see, I included a type property with a value of module. Doing this tells the browser that we'll be using JS Modules and main.js is our top level module, which includes keywords like export
, import
, and *
(asterisk symbol for 'all'). We don't need to include any of our scripts because our main.js module will import everything else that it needs.
One thing to note is that you need to work on this through a server. Brackets comes with a built in "live preview" which launches a local web server. You can use XAMPP or anything else. Loading modules with a file:// or c:// prefix will cause errors due to CORS requirements. In my video, you'll notice that I'm using a server running on localhost (127.0.0.1).
Creating and Exporting Modules:
Modules just contain JavaScript code, whether they are methods or just variables. You can export
them in two ways. The first way is to define your function and variable as shown below, and at the end of the file, use the export
keyword and put all of your variable and method names in curly braces, as if you were creating a weird array type object:
const current = 100; // we are naming a constant 'current' // Simple "funnyCase" method shown in the video function funnyCase(text) { let funnyText = ''; text.split('').map( (t, i) => { funnyText += (i%2 === 0) ? t.toUpperCase() : t.toLowerCase(); }); return funnyText; } // We export our variable and method names as shown below export {current, funnyCase};
Pretty simple, right? The second method is also pretty simple. You can export
your code as you write them like so:
export function twiceRadius(rad) { return 2 * (Math.PI * rad * rad); } export function powerOfFive(num) { return Math.pow(num, 5); }
By including the export
keyword before the method names, we're exporting them as we go.
To import
them into our main module, we can use a few different syntax. The first and easiest is to just select everything in a particular module. This is where the asterisk comes into play. We can also assign an alias to our import
so that we can call the defined methods in a more structured way like so:
import * as texts from './moduleOne.js';
The texts is our alias so if we define a method named funnyCase within moduleOne.js
, we can call it with texts.funnyCase(args)
. But what if you want to just import some things and not everything? That's easy too:
import {twiceRadius, current, powerOfFive as pof} from './moduleTwo.js';
Because our methods are named, we can use the import keyword and input all of the names of our exported methods and variables in curly braces as shown above. We can also assign an alias as we did with powerOfFive as pof
. You can then call the methods as you see fit.
Hope you learned something about JavaScript modules. There's no fiddle associated with this tutorial but you can find the files in the video on Github (https://github.com/naztronaut/JavaScript-Modules-tutorial) or at the following URL: https://www.easyprogramming.net/downloads/javascript/modules/
JavaScript modules can be extremely powerful. I tend to use them to create templates for my HTML because it makes things neater and easier to manage.
If you have questions, feel free to ask! Remember to come back for more tutorials.
Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!
To fork the files on Github, find them here: https://github.com/naztronaut/JavaScript-Modules-tutorial
If you have issues with Github, you can also find them here: https://www.easyprogramming.net/downloads/javascript/modules/
For the JS files see these links:
https://www.easyprogramming.net/downloads/javascript/modules/main.js
https://www.easyprogramming.net/downloads/javascript/modules/numberModule.js
https://www.easyprogramming.net/downloads/javascript/modules/textModule.js