DEV Community

Cover image for A guide to through async/await with Babel and Webpack
Bertil Tandayamo
Bertil Tandayamo

Posted on

A guide to through async/await with Babel and Webpack

At first, the JavaScript projects with Webpack ran well. Then I realized that our project should be able to run on an outdated browser, so I chose Babel. I subsequently installed and ran it.

The projects include a beautiful restaurant page and a cool design to-do list app. Then APIs came into the scenario. Inevitably I had to deal with promises. I can handle them with .then or async/await functions.

I decided to go with async/await, to write the API function




const getDataByIpCheck = async () => {
    const response = await fetch(
      `http://api.ipstack.com/check?access_key=${process.env.API_KEY_IPSTACK}&format=1`
    );
    return response.json();
  };
  };


Enter fullscreen mode Exit fullscreen mode

I ran the application npm run start and 😮, but what's going on, I got an error

image

What are we going to do?. I could've cried over our keyboard but I chose to find a solution.

This was the solution 💡


What @babel/polyfill is?

It's just the import of stable core-js features and regenerator-runtime for generators and async functions, so if you load @babel/polyfill - you load the global version of core-js without ES proposals.

Install babel-polyfill

I'm assuming that you've already installed all webpack dependencies, along with babel config inside webpack config file

Through npm add this dependency npm install --save @babel/polyfill to your project

Update webpack file

At the beginning in the module.export object, entry key add
entry: ["@babel/polyfill", "<your enter js file>"]

Your file should look like the below



module.exports = {
  mode: 'development',
  entry: ['@babel/polyfill', './src/index.js'],


Enter fullscreen mode Exit fullscreen mode

Run again npm run start

image.png

And voilà the project now works.

Conclusion

@babel/polyfill allows us to emulate a full ES2015+ environment, in this case, to work with async/await promise functions. Polyfill adds a global scope to accomplish this


I'd be grateful if you could leave a comment if you found this post helpful or liked it.

Please follow @btandayamo on Twitter

Top comments (3)

Collapse
 
aorcsik profile image
Antal Orcsik

According to @babel/polyfill documentation, it is now deprecated and can be replaced by adding core-js and regenerator-runtime as dependency and importing them directly to your webpack entry js file:

import "core-js/stable";
import "regenerator-runtime/runtime"; 
Enter fullscreen mode Exit fullscreen mode

I've tried it, works perfectly.

Collapse
 
letsbsocial1 profile image
Maria Campbell

Did not know this, and I couldn't get my async awaits to work until I added this polyfill. Thanks for sharing!

Collapse
 
btandayamo profile image
Bertil Tandayamo

glad to help