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
Top comments (3)
According to @babel/polyfill documentation, it is now deprecated and can be replaced by adding
core-js
andregenerator-runtime
as dependency and importing them directly to your webpack entry js file:I've tried it, works perfectly.
Did not know this, and I couldn't get my async awaits to work until I added this polyfill. Thanks for sharing!
glad to help