Transpiling Javascript

When using modern ES6+ syntax and features (which some of our code snippets do), it is important to transpile your code and include polyfills to ensure your code works in older browsers, such as IE11.

The recommended way to do this is to set up a build system that converts your ES6+ code to ES5, using a library such as Babel or Parcel.

Babel

First we need to install Babel as a dev dependency into our project.

sh

1npm i --save-dev @babel/core @babel/cli @babel/preset-env

The next step is configuring Babel to use the env preset, which will ensure your code is browser compatible. To do this, we create a .babelrc file at the root of our project, and then add the following code:

JSON

1{
2 "presets": ["@babel/preset-env"]
3}

Now we can create a build command that will transpile our code. In your package.json file (create one if it doesn't exist), add the following script:

sh

1...,
2"scripts": {
3 "build": "npx babel src -d build"
4}

This script will take any code in src, and output the transpiled code into the build folder.

Now when you're ready to transpile your code, simply run npm run build, and you'll get production ready code placed into the build folder!

There are other ways to use Babel as well. Here are some resources to get you started with more complex build systems:

Parcel

Parcel is a module bundler, similar to Webpack, except it comes completly preconfigured out of the box. It is extremely easy to use, and you can be up and running in a few seconds with no configuration.

The first step is installing Parcel as a dependency:

sh

1npm install -g parcel-bundler

And then all you have to do is create a build script! In your package.json file (create one if you don't have one already), add the following script:

sh

1...,
2"scripts": {
3 "build": "parcel build src/index.js"
4}

In this case src/index.js is our entry point (feel free to change this to suit your needs).

Now when you're ready to transpile your code, simply run npm run build, and you'll get production ready code placed into the build folder!

Parcel also has many other easy to use features, such as a built in dev server and code splitting. Here is the documentation to get you started.

Other resources

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales