JavaScript programs in CodeHS now support ES modules. This tutorial shows you how to make the most of them in your JavaScript programs!
In JavaScript, modules are discrete programs that can be imported into other programs as needed. Modules allow the programmer to reuse code or create abstraction boundaries. As we’ll see in this tutorial, they also provide a way to share your code for others to use.
Let’s look at a sample program that uses modules. This program has a single import statement, which loads code hosted on a website at codehs.me.
The code for the module is hosted on a separate site, but it’s imported directly into the program when it runs.
Loading modules lets you be part of the worldwide coding community!
You can load libraries written by anyone, hosted on sites like npm.
Here’s a program that loads the ml5js library to use machine learning and the p5js library to create an interactive canvas. The program will use a machine learning model to classify your doodle and guess what you’ve drawn. Give it a try!
The easiest way to create your own module in CodeHS is to add a JavaScript file to your CodeHS.me homepage, which you can edit here.
Add an export
statement to your module, then import it in one of your JavaScript programs using a statement like import 'https://andy.codehs.me/module.js'
.
Created a module you’re proud of or think others might find useful? Share it with us on Twitter @CodeHS!