0

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
jet2016
  • 345
  • 1
  • 3
  • 11

1 Answers1

0

When using @babel/preset-env, you have to specify an option for how it transpiles your module syntax. If you want your babel configuration to target ES6 modules and to not transform ES6 module syntax, you have to modify your config to include this option:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "modules": false,
        "targets": {
          "esmodules": true
        }
      }
    ]
  ]
}

Refer to the docs here for more information on this

awarrier99
  • 3,628
  • 1
  • 12
  • 19
  • Sorry, my fault. Now I have included the source code. In my setup I am already using `import axios from 'axios' ` – jet2016 May 13 '20 at 21:48
  • @jet2016 no problem, but can you also include the full stack trace of the error? – awarrier99 May 13 '20 at 21:50
  • I have also included the snippet to be run. – jet2016 May 13 '20 at 22:00
  • @jet2016 I just updated my answer which should solve your problem – awarrier99 May 13 '20 at 22:02
  • Sorry, I had little time to check. Your answer regarding `.babelrc` solved part of my mistakes. I think I have only one conceptual issue now to understand regarding es6 modules. I am transpiling the code and still **axios** library is not included in the modules. I run the transpiled code in the browser and that is the problem I am facing now. This is the error in the console: `TypeError: Error resolving module specifier: axios` This comes from the above code in `user.js` – jet2016 May 14 '20 at 17:34
  • @jet2016 if you don't plan on using `webpack`, you may be better off including `axios` directly as a script in your HTML. Without `webpack`, your code doesn't know what you're referring to when you write just `axios`, since no module resolution is done. Refer to [this](https://stackoverflow.com/questions/52558777/import-from-node-modules-not-recognized-in-es6-modules-in-browser) question for more info. You can either try importing directly from `node_modules`, or start using `webpack` or some other bundling tool – awarrier99 May 14 '20 at 22:16
  • @jet2016 also [here](https://medium.com/@dmnsgn/es-modules-in-the-browser-almost-now-3638ffafdc68) is a good article explaining better why this doesn't work – awarrier99 May 14 '20 at 22:20
  • 1
    All this fuss came from the fact that Parcel, my builder of choice, does not handle correctly `async` code inside modules. There are number of issues open on this matter. I have also learnt that `àxios` does not currenly have esm version to be able to use it with import module syntax within the browser. So I ended up using an extra `` tag in my html with defer attribute and now works well. Thanks for your support awarrier99. – jet2016 May 16 '20 at 17:53