Issue
I am testing axios within an es6 module and getting this error in the console when running the site in the browser:
ReferenceError: require is not defined
I know what the error means but I was expecting that Babel would transpile everything to ES5. So I suppose the problem is my setup.
Remark: This is just a test of async modules. Not trying to use the best possible code for production.
Environment (inc. source code)
relevant info from package.json
"devDependencies": {
"@babel/cli": "^7.8.4",
"@babel/core": "^7.9.6",
"@babel/preset-env": "^7.9.6"
},
"dependencies": {
"axios": "^0.19.2"
}
contents of .babelrc
{
"presets": ["@babel/preset-env"]
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/axios@0.19.2/dist/axios.js" defer></script>
<script type="module" src="./js/main.js"></script>
</head>
<body>
<div class="container">
<div id="user"></div>
</div>
</body>
</html>
main.js
import user from './components/user.js'
const app = async () => {
document.getElementById('user').innerHTML = await user()
}
// init app
app()
user.js
const user = async () => {
const res = await axios.get('https://randomuser.me/api')
const rand_user = res.data.results[0]
const template = `
<div class="card">
<img src="${rand_user.picture.large}" alt="rand_user" />
<div class="card-body">
<p>hello from template</p>
</div>
</div>
`
return template
}
export default user