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.
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.
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.
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
import
resources