Breakdown of 7 different ways to use ES modules with npm today.
Breakdown of 7 different ways to use ES modules with npm today.
ES Modules are the future of JavaScript, but unlike many other es@next features that developers have raced to take advantage of mainly thanks to build tools like babel, working with ES modules alongside of existing NPM modules is a lot harder to get started with.
The purpose of this tutorial is to provide a thorough set of examples for different ways you can approach writing ES modules, without losing interop with the vast library of mostly commonjs modules that exist on NPM today.
We'll start with a naive ES module in step 1 and work our way through a series of increasingly complex example approaches, all of which are intended to define the same, basic module.
Every approach must satisfy the following requirements:
The functionality of our example NPM module is a bit contrived, but it should touch on all the potential pain points, and trust me, there are a lot of them...
Every approach will define an NPM module with a single default export, async getImageDimensions(input)
, that takes in an image and returns its { width, height }
.
To show how you can bundle modules with slightly different semantics for Node.js and the browser:
input
as a string
that can either be a local path, http url, or data url.input
as a string
URL or an HTMLImageElement
.Both versions return a Promise
for { width: number, height: number }
.
MIT Travis Fischer
Support my OSS work by following me on twitter