无法解析模块说明符“firebase/app”

MrB*_*oka 8 html javascript firebase

这是我第一次使用 Firebase,我认为我已经按照所有步骤将我的项目连接到 Firebase。我尝试用一​​个小程序运行我的项目js console.log(firebase)当我进入控制台时,我收到了此错误消息Failed to resolve module specifier "firebase/app"

我想提一下,我已经创建了一个 node_module 文件夹,并且执行了 npm i firebase。

html 文件:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>TP1</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
        <script type="module" src="/index.js"> </script>
    </head>
    <body>
Run Code Online (Sandbox Code Playgroud)

索引.js:

import { initializeApp } from "firebase/app";
//import { getDatabase } from "firebase/database";

const firebaseConfig = {
  //(my config...)
};


const app = initializeApp(firebaseConfig);
//const database = getDatabase(firebaseConfig);

console.log(firebase)
Run Code Online (Sandbox Code Playgroud)

Rob*_*999 17

要在没有 Webpack 或 Rollup 的情况下运行 Firestore,请跳过 npm 安装并将导入行替换为 Firestore 的浏览器模块引用。这里解释一下:

https://firebase.google.com/docs/web/setup?sdk_version=v9&authuser=0 (在步骤 2 中)。

该视频也很有帮助,它解释了 Firebase 的新(V9 中)模块化/功能与已弃用的 object.method 模型。

以下是我的 JS 模块如何将 Firestore 连接到我开发的 Web 应用程序:

// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.1/firebase-app.js";
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.1.1/firebase-firestore.js"
import { collection, getDocs, addDoc, Timestamp } from "https://www.gstatic.com/firebasejs/9.1.1/firebase-firestore.js"
import { query, orderBy, limit, where, onSnapshot } from "https://www.gstatic.com/firebasejs/9.1.1/firebase-firestore.js"
// 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
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxx.firebaseapp.com",
projectId: "xxxx9",
storageBucket: "xxxxx.appspot.com",
messagingSenderId: "xxxxx",
appId: "1:xxx:web:xxx"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

export { app, db, collection, getDocs, Timestamp, addDoc };
export { query, orderBy, limit, where, onSnapshot };
Run Code Online (Sandbox Code Playgroud)

  • 在引用脚本的脚本标记中包含“type =”module”。例如: &lt;script src=”./index.js” type=”module”&gt;&lt;/script&gt; (3认同)

sam*_*man 7

当您使用 时import { ... } from "some/package",您应该在网站上访问代码之前使用WebpackRollup等捆绑程序来编译代码。这将从依赖项中提取出您需要的部分,以供您的代码使用。

特别是在 SDK 的 v9+ 中,Firebase SDK 被重写以支持这些捆绑器,因此您看到的许多代码示例是为现已弃用的 v8 或更早版本编写的。本迁移指南介绍了如何移动这些旧代码。

该指南的一个关键要点是它firebase不再是一个全局对象。由于您是 Firebase 新手,我会避免编写任何使用旧语法的代码。您可以通过查找firebase.initializeApp()firebase.database()等代码来发现较旧的语法firebase.firestore()。在 SDK 中,这些示例已分别替换为initializeApp()getDatabase()getFirestore()

如果您打算直接在浏览器中使用模块化代码(使用<script type="module" src="..."></script>),请务必记住该代码与浏览器控制台隔离 - 您不能运行console.log(firebaseConfig)并期望它拥有您的对象。

下一部分不适合生产代码,只是为了在熟悉的环境中尝试。

如果您想在浏览器控制台中修改 Firebase 库,您将添加与此类似的内容:

<script type="module">
  window.FIREBASE_MODULES = window.FM = {};

  async function loadFirebaseModule(serviceName, sinkErrors) {      
    const name = serviceName.toLowerCase();
    if (window.FIREBASE_MODULES[name]) return window.FIREBASE_MODULES[name];
      
    try {
      // uses unpkg to get the latest semver
      if (!loadFirebaseModule.version) {
        const response = await fetch("https://unpkg.com/firebase/firebase-app.js", { method: "HEAD" });
        const match = /@\d+(?:\.\d+)*/.exec(response.url);
        if (!match) {
          console.log("Unexpected resource URL (SemVer could not be determined, falling back to v9.0.0): " + response.url);
          loadFirebaseModule.version = "9.0.0";
        } else {
          loadFirebaseModule.version = match[0].slice(1);
        }
      }
      
      // use the found semver to pull from Google's CDN
      const module = await import(`https://www.gstatic.com/firebasejs/${loadFirebaseModule.version}/firebase-${name}.js`);
      window.FIREBASE_MODULES[name] = module;
        
      console.log(`Successfully imported "${name}" module`)
      return module;
    } catch (err) {
      if (sinkErrors) {
        console.error(`Failed to import "${name}" module`, err);
      } else {
        throw err;
      }
    }
  }
  window.loadFirebaseModule = loadFirebaseModule;
</script>
Run Code Online (Sandbox Code Playgroud)

现在,这个小片段将允许您在页面内或浏览器控制台中运行这样的代码。它返回一个 Promise,因此如果您在脚本中使用它,请务必等待它完成解析。

loadFirebaseModule('app')
  .then(({ initializeApp }) => {
    initializeApp({ /* ... config ... */ });
  });

loadFirebaseModule('storage');
loadFirebaseModule('storage', true); // import & ignore the error
Run Code Online (Sandbox Code Playgroud)

加载模块后,您可以const { getApp } = FM.app像使用import { getApp } from "firebase/app".