Image for post
Image for post

ES6 modules, Node.js and the Michael Jackson Solution

Alberto Gimeno
Jul 21, 2017 · 6 min read
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><script>
// `$` variable available here
</script>
Image for post
Image for post

CommonJS to the rescue

Image for post
Image for post

How ES6 modules work and why Node.js hasn’t implemented it yet

const { helloWorld } = require('./b.js') // CommonJS
import { helloWorld } from './b.js' // ES modules
// CommonJS
exports.helloWorld = () => {
console.log('hello world')
}
// ES modules
export function helloWorld () {
console.log('hello world')
}
// index.html
<script type="module" src="./a.js"></script>
// a.js
console.log('executing a.js')
import { helloWorld } from './b.js'
helloWorld()
// b.js
console.log('executing b.js')
export function helloWorld () {
console.log('hello world')
}
executing b.js
executing a.js
hello world
// a.js
console.log('executing a.js')
import { helloWorld } from './b.js'
helloWorld()
// b.js
console.log('executing b.js')
export function helloWorld () {
console.log('hello world')
}
executing a.js
executing b.js
hello world
<script type="module" src="./a.js"></script>
Image for post
Image for post

A note about Babel

Image for post
Image for post

Why ES6 modules are good and how to get the best of both worlds

const provider = process.env.EMAIL_PROVIDER
const emailClient = require(`./email-providers/${provider}`)
Image for post
Image for post

DailyJS

JavaScript news and opinion.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store