【问题标题】:es6 async modules with axios - ReferenceError: require is not defined带有 axios 的 es6 异步模块 - ReferenceError: 未定义要求
【发布时间】:2020-05-13 21:07:26
【问题描述】:

问题

我在 es6 模块中测试 axios,并在 浏览器 中运行站点时在控制台中收到此错误:
ReferenceError: require is not defined
我知道错误是什么意思,但我期待 Babel 会将所有内容转换为 ES5。所以我想问题出在我的设置上。
备注:这只是对异步模块的测试。不尝试将最好的代码用于生产。

环境(包括源代码)

来自package.json的相关信息

  "devDependencies": {
    "@babel/cli": "^7.8.4",
    "@babel/core": "^7.9.6",
    "@babel/preset-env": "^7.9.6"  
  },
  "dependencies": {
    "axios": "^0.19.2"
  }

.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

【问题讨论】:

  • 也分享你的代码
  • 控制台错误指向哪一行?我在您的代码中没有看到任何require 的用法
  • 我刚刚添加了所有代码,包括最后的转译代码。 Require 在转译的 JS 中。
  • @jet2016 啊,现在更有意义了。我更新了我的答案

标签: javascript babeljs


【解决方案1】:

当使用@babel/preset-env 时,您必须指定一个选项来说明它如何转译您的模块语法。如果您希望 babel 配置以 ES6 模块为目标并且不转换 ES6 模块语法,则必须修改配置以包含此选项:

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

有关更多信息,请参阅文档here

【讨论】:

  • 对不起,我的错。现在我已经包含了源代码。在我的设置中,我已经在使用import axios from 'axios'
  • @jet2016 没问题,但是你能不能也包括错误的完整堆栈跟踪?
  • 我还包含了要运行的 sn-p。
  • @jet2016 我刚刚更新了我的答案,应该可以解决您的问题
  • 所有这些大惊小怪都是因为我选择的构建器 Parcel 没有正确处理模块内的 async 代码。在这个问题上有许多问题悬而未决。我还了解到àxios 目前没有 esm 版本,无法在浏览器中使用导入模块语法。所以我最终在我的 html 中使用了一个额外的 &lt;stript&gt; 标记和 defer 属性,现在效果很好。感谢您对 awarrier99 的支持。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 2019-12-18
  • 2017-11-25
  • 1970-01-01
  • 2021-01-06
  • 2015-06-12
相关资源
最近更新 更多