NodeJS and Common JS
Time Box
Activity | Time |
---|---|
Reading | 0.5 hours |
So far we've been discussing JavaScript Modules for the browser.
On the server we'll use NodeJS, which runs JavaScript a little different to the browser. This document is going to discuss those differences a little but we won't really get into the details until bootcamp.
In particular it was built on a different way of writing modules called CommonJS. I'm not going to get into too much detail, but it's a similar idea with different syntax.
In $CURRENT_YEAR
NodeJS does have support for standards based JavaScript Modules, but things can get a little weird.
By default NodeJS will treat files with names that end in .js
as CommonJS modules. This means that you cannot use the import
/export
keywords in them. If a file name ends in .mjs
, then Node will treat it as a standards-based JavaScript Module and you will be able to import
and export
. Remember that the Browser does not care what the url of a script ends with, it only cares that you use type="module"
in the script tag that loads your JavaScript.
There are other circumstances where NodeJS will treat your javascript as a JavaScript Module, but the rules get pretty complicated. Most of the time, the simplest way to use ESM with NodeJS is to have .mjs
at the end of your filename.
So, to reuse a previous example, with these two files:
// hype-the-crowd.mjsexport default function hypeTheCrowd(call, response) {console.log(`When I say ${call}, you say ${response}!`)console.log(`ME: ${call.toUpperCase()}!`)console.log(`CROWD: ${response.toUpperCase()}!`)console.log(`ME: ${call.toUpperCase()}!`)console.log(`CROWD: ${response.toUpperCase()}!`)console.log(`ME: I can't hear you!`)}
// main.mjsimport hypeTheCrowd from './hype-the-crowd.mjs'hypeTheCrowd('cheese', 'cake')hypeTheCrowd('hot', 'dog')
If you run this in your terminal it might look like this:
~/node-hype $ node ./main.mjsWhen I say cheese, you say cake!ME: CHEESE!CROWD: CAKE!ME: CHEESE!CROWD: CAKE!ME: I can't hear you!When I say hot, you say dog!ME: HOT!CROWD: DOG!ME: HOT!CROWD: DOG!ME: I can't hear you!