A guide to through async/await with Babel and Webpack

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();
  };
  };

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

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'],

Run again npm run start

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