Search code examples
javascriptbabeljsecmascript-5ecmascript-2017

Compile asyn/await to es5 with babel js


I have really small project with single .html file and one .js file. The problem that I used asyn/await functions so I need to convert it to es5 to be sure that everything works fine.

So, my .html file looks like this:

<html>
 <head>
 </head>
 <body>
   ...//page markup

   <script src="dist/myCodeAsES5.js"></script>

   <script>
    var obj = new MyClass();
    obj.calculate();
   </script>

 </body>
</html>

And here my src.js

class MyClass{

    constructor(){
        this.calculate = async function () {
           await func1();
        }
    }

    async function func1() {
      for (var i = 0; i < 3; i++) {
         await func2(); // await in loop until func2() completed 
      }
    }

    async function func2() {
       for (var i = 0; i < 10; i++) {
         await func3(); //wait until func3 and then continue looping
       }
    }

    function func3() {
      return new Promise(resolve => setTimeout(resolve, 1000));
    }


}

Now the main question- how to convert it to es5 so it can be 100% woks in Internet Explorer. I had read a lot about "babel" but everything that I found is not understandable or out of date. So can somebody write a short step-by-step guide how to install and compile that small project?


Solution

  • assuming you want to quickly run a script to transpile your es5 code with babel follow these instructions:

    • first thing you have todo is to setup a little node project. if you have never setup a node project goto: https://nodejs.org/en/download/

    • as soon as you have npm globally you can goto your project folder and type: npm init this will create you a package.json file.

    • goto: https://babeljs.io/docs/setup/#installation and click on CLI and follow all the mentioned steps.

    • Make sure you install the correct presets for babel to transpile async await. You'll need the es2015 and stage3 preset and the runtime plugin.

      • http://babeljs.io/docs/plugins/preset-es2015/#install
      • http://babeljs.io/docs/plugins/preset-stage-3/#install
      • https://babeljs.io/docs/plugins/transform-runtime/#installation
      • checkout Transpile Async Await proposal with Babel.js? for a more minimal setup.