【问题标题】:I'm getting an error when I try to import modules. What Can I do? [duplicate]尝试导入模块时出现错误。我能做些什么? [复制]
【发布时间】:2021-10-26 14:44:12
【问题描述】:

我正在尝试在我的小站点上使用 firebase 的 Firestore 数据库,我从 https://firebase.google.com/docs/firestore/manage-data/add-data 获取了他们的代码。我首先在一个内置的 html 脚本中使用了这些配置,但我将它移到了一个文件中。然后我添加了代码,它给了我

SyntaxError: Unexpected token '{'
at /script.js:19:10

这是我的代码:

HTML

  <body>
    <input type="text" placeholder="type something">
    <input type="submit">
    <script src="script.js" type="module"></script> <!-- This is where my script is. -->
  </body>

Javascript (script.js)

// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
      
const firebaseConfig = { //I don't know if these are sensitive, so i'm censoring them. 
  apiKey: "**",
  authDomain: "**",
  projectId: "**",
  storageBucket: "**",
  messagingSenderId: "**",
  appId: "**"
};

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



function writeTest() {
  import { doc, setDoc, Timestamp } from "firebase/firestore"; //this is where it says the error is.



  const docData = { //this is just test data straight from the site
      stringExample: "Hello world!",
      booleanExample: true,
      numberExample: 3.14159265,
      dateExample: Timestamp.fromDate(new Date("December 10, 1815")),
      arrayExample: [5, true, "hello"],
      nullExample: null,
      objectExample: {
          a: 5,
          b: {
              nested: "foo"
          }
      }
  };
  await setDoc(doc(db, "data", "one"), docData);
}

【问题讨论】:

  • 我应该使用实时数据库吗?”这里的帖子预计将集中讨论一个可以用事实和来源回答的技术问题。由于您已经在上面提出了另一个核心问题,并且考虑到这个问题是高度基于意见的(它主要是根据您的特定要求和约束而做出的设计决策),因此应该将其完全从您的问题中删除。 How to Ask
  • @esqew 我的错,添加它真的是事后才想到的。我会删除它。感谢您的澄清。
  • 也许导入不应该位于 writeTest() 函数内,而是位于顶层(/+ 在文件开头)?
  • 简而言之,您在该行使用的语法是错误的,这就是它抛出该错误的原因;要在该行上导入,您需要使用动态导入。最重要的是,对于您的第一行,我很确定这也是无效的语法。有问题的模块需要在您的代码库中本地; Deno 是唯一允许从 url 进行外部导入的引擎。

标签: javascript html firebase google-cloud-firestore


【解决方案1】:

这就是我设置 firestore 的方式 - 不同的方式,但它可以工作,所以它可能会有所帮助

index.html
    <script defer src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
    <script defer src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>    
    <script defer src="/firebase-init.js"></script>
firebase-init.js
"use strict";

const firebaseConfig = { 
  apiKey: "**",
  authDomain: "**",
  projectId: "**",
  storageBucket: "**",
  messagingSenderId: "**",
  appId: "**"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

let db = firebase.firestore();

db.collection(collection).doc(docID).get().then(docObj => {})  // read document
db.collection(collection).doc(docId).set(docObj)  // write document to db


【讨论】:

    猜你喜欢
    • 2022-12-07
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    相关资源
    最近更新 更多