Enabling Async/Await and Generator Functions in Babel and Node JS
Looking for a great (remote only) React Dev? Visit my profile on LinkedIn and say hi! 😃
Babel needs a little extra love if you want to transpile Async/Await or Generator Functions (link to docs).
My project uses Babel inside of Webpack, together with Node Express and React. Previously, this was my .babelrc:
{
"presets": [
"env", "react"
]
}
When I tried to implement Async this way, I received the following error:
Uncaught ReferenceError: regeneratorRuntime is not defined
I found this answer to my troubles and it worked when I implemented it. Just change .babelrc to the following:
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "10"
}
}
],
"@babel/preset-react"
]
}
Now you can Async, Await, and Generate to your hearts’ content.
async function getData() {
console.log('Check 1') await fetch('http://localhost:8080/getExchangeData')
.then(resp => resp.json())
.then(data => console.log(data)) console.log('Check 2')
}
Happy coding! =)