【问题标题】:JS : Uncaught SyntaxError: Cannot use import statement outside a moduleJS:未捕获的语法错误:无法在模块外使用 import 语句
【发布时间】:2022-03-02 12:39:26
【问题描述】:

我正在学习 Firebase。我正在使用 Kubuntu 21.04。 我使用 :
sudo apt install nodejs npm 安装了 nodejs 和 npm 我用 index.html 文件 /home/username/project/index.html 创建了一个项目文件夹。
当我在终端的项目文件夹中时,我还使用 npm install firebase 安装了 firebase
我按照 https://firebase.google.com/docs/web/setup 中给出的 STEP 2 进行操作。
我的 index.html 内容-

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>User Auth</title>
</head>
<body>
  <h1>User Auth</h1>

<script>
  // Import the functions you need from the SDKs you need

  import { initializeApp } from "firebase/app";
  import { getAnalytics } from "firebase/analytics";


  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  const firebaseConfig = {
    apiKey: "AIzaSyC5zv8b1wfc0ykmpULeFI6tJa6Grk",
    authDomain: "user-auth-75223.firebaseapp.com",
    projectId: "user-auth-78563",
    storageBucket: "user-auth-78563.appspot.com",
    messagingSenderId: "482788408547",
    appId: "1:482788408547:web:89e3ecdc24f3454576c00aa",
    measurementId: "G-VK5D45CCJ2"
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);
</script>
</body>
</html>

但是当我在 chrome 中运行上面的 html 文件时。它在 chrome 的控制台中给出错误。

未捕获的语法错误:无法在模块外使用 import 语句

【问题讨论】:

  • &lt;script&gt; 需要将type="module" 添加到其中。
  • 如果您正在学习使用 Firebase 构建 Web 应用程序,最好遵循以下指南,这样您也可以学习相关的最佳实践。 developers.google.com/codelabs/…blog.angular-university.io/angular-2-firebase
  • @evolutionxbox 现在给出“索引错误”:未捕获的类型错误:无法解析模块说明符“firebase/app”。相对引用必须以“/”、“./”或“../”开头。
  • 是的。如果您直接在浏览器中使用模块,则不能在不使用绝对或相对引用的情况下使用 npm 模块。如果你不想这样,请使用 webpack 之类的打包工具。
  • @evolutionxbox 我的项目文件夹中有一个名为 node_modules 的文件夹。 /project/node_modules.

标签: javascript node.js firebase


【解决方案1】:

可能是因为你没有添加 "type":"module" 在 package.json 中?

我通过添加这一行解决了这个问题

来源: (node:9374) Warning: To load an ES module, set "type": "module"

【讨论】:

  • 如果问题被其他人回答,请将其标记为重复。
猜你喜欢
  • 1970-01-01
  • 2020-10-04
  • 2021-05-15
  • 2023-03-17
  • 2020-10-10
  • 2020-10-25
  • 2020-09-19
相关资源
最近更新 更多