JavaScript offers us more than one way to handle modules. Each of them is dedicated to the specific situation: client or browser. So, let’s dive right in and see how we can use them properly.

Client side

The most old-school way of modules in javascript is just creating multiple .js files and importing them in .html file. Like this.

    ...
    <script src="helpers.js"></script>
    <script src="main.js"></script>
  </body>
</html>

But this setup to work properly require everything important for us to be a global variable.

Thankfully at this moment all modern browser supports ES6 import keyword.

Can I Use es6-module? Data on support for the es6-module feature across the major browsers from caniuse.com.

Let’s see how it would look in the code

// helpers.js
export function adder (x, y) {
  return x + y
}

// main.js
import { adder } from './helpers.js'
    ...
    <script type="module" src="main.js"></script>
  </body>
</html>

That’s great because we can import only what we need. However, if we would like some more advanced features or support legacy browsers we definitely need some properly configurated bundler like webpack.

Server Side

Node.js supports modules out of the box, but the syntax is a little bit different. The default keyword is require and we must explicitly define what we want to expose in module.exports object.

// helpers.js
const adder = (x, y) => x + y
module.exports = {
  adder
}

// main.js
import { adder } from './helpers.js'

Of course, if we add configure bundler we can also use import/export syntax in Node.js. But there are some slight differences:

require

  • dynamic evaluation
  • throws an error at runtime

import

  • static evaluation
  • throws while parsing

resources


Karol Świeca

My thougths on JavaScript, AWS Cloud and other aspects of being Software Engineer