Skip to content

Using ES6 (WIP)

andrewgordstewart edited this page Jun 24, 2018 · 3 revisions

We want to use ECMAScript in our packages. In order for this to be ok as a node module, the code needs to be transpiled to CommonJS. There are two options:

  1. We transpile it prior to publishing with babel.
  2. We use ESM, which transpiles on-the-fly, with a minimal performance hit.

Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in old browsers or environments.

This means we get to use fancy EMScript features in our libraries, without requiring that our users need an EMScript-compatible environment.

Check out this post for an overview of the toolchain.

babel-polyfill or babel-runtime?

This stack-overflow answer has a quick overview of the difference between babel-polyfill and babel-runtime. This is covered in the above blogpost as well.

Lerna

As we've split our force-move-games project into packages, we're using lerna to manage it. The docs are great. The short of it is that lerna bootstrap will:

  1. npm install all external dependencies of each package.
  2. Symlink together all Lerna packages that are dependencies of each other.
  3. npm run prepublish in all bootstrapped packages.
  4. npm run prepare in all bootstrapped packages.

We can therefore add "prepare": "./node_modules/.bin/babel src --out-dir lib" to the "scripts" field of package.json. When we run lerna bootstrap, it will then transpile our src code into the lib directory, which is ignored by git.

A fast, production ready, zero-dependency ES module loader for Node 6+!

ESM provides an easier, fewer-moving-parts solution, with less backwards-compatible support and a small performance hit.

Getting it started is easy. Only fmg-core is intended to be consumed. If we wish to add CJS support to fmg-payments, we would have to add the boilerplate to fmg-payments/index.js as well as update fmg-payments/package.json accordingly.

There are no dependencies required by the consumer of the module -- the ES6 code is transpiled to CJS code on-the-fly inside the module itself.

However, when you run truffle test, index.js doesn't get loaded before loading the test files. So, to write tests in ES6, we need to load it locally. Since lerna run test uses npm test, this lets us test our entire project with ease.