2

我正在尝试将 firebase 代码添加到 Vuepress 中,这样我就可以将一个简单的评论应用程序嵌入到所有 Vuepress 页面中。想知道如何做到这一点?

```

<script src="https://www.gstatic.com/firebasejs/5.5.6/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "asdf",
    authDomain: "adsf-9e0b6.firebaseapp.com",
    databaseURL: "https://asdf-9e0b6.firebaseio.com",
    projectId: "sadf-9e0b6",
    storageBucket: "adsf-9e0b6.appspot.com",
    messagingSenderId: "asdf"
  };
  firebase.initializeApp(config);
</script>

```

4

2 回答 2

2

Add something like this in the config.js within the head array. Note that this adds firebase-app (core), firebase-auth, firestore, and cloud functions as I'm using 4 modules in my project.

NOTE that I'm also initializing both firebase and firestore in here. So I get firestore as a global variable.

When firebase loads, all these will be hoisted to the head section of the app.

 head: [

    [
      "script",
      {
        src: "https://www.gstatic.com/firebasejs/5.5.6/firebase-app.js"
      }
    ],

    [
      "script",
      {
        src: "https://www.gstatic.com/firebasejs/5.5.6/firebase-auth.js"
      }
    ],

    [
      "script",
      {
        src: "https://www.gstatic.com/firebasejs/5.5.6/firebase-firestore.js"
      }
    ],

    [
      "script",
      {
        src: "https://www.gstatic.com/firebasejs/5.5.6/firebase-functions.js"
      }
    ],

    [
      "script",
      {},
      `var config = {
        apiKey: "apikey",
        authDomain: "app.firebaseapp.com",
        databaseURL: "https://app.firebaseio.com",
        projectId: "appname",
        storageBucket: "appname.appspot.com",
        messagingSenderId: "12345"
      };
      firebase.initializeApp(config);
      const firestore = firebase.firestore();
      const settings = { /* your settings... */
          timestampsInSnapshots: true
      };
      firestore.settings(settings);`
    ],
    ]
于 2018-11-02T19:47:42.540 回答
0

为避免 Vuepress 构建站点时出错,您需要仅在客户端运行 Firebase 初始化。

谷歌转向更通用的配置模型。它建议使用自动获取配置参数的包含。

我的回答还包括启用 Firebase 分析。

config.js head数组中:

    ["script", {src:"/__/firebase/8.2.1/firebase-app.js"}],
    ["script", {src:"/__/firebase/8.2.1/firebase-analytics.js"}],

enhanceApp.js

function loadJavaScriptAsync(file, onload) {
  const script = document.createElement("script");
  script.type = "text/javascript";
  script.src = file;
  script.onload = onload;
  document.body.appendChild(script);
}

export default ({
  Vue, // the version of Vue being used in the VuePress app
  options, // the options for the root Vue instance
  router, // the router instance for the app
  siteData, // site metadata
  isServer
}) => {
  if (!isServer && !window.location.href.startsWith("http://localhost")) {
    loadJavaScriptAsync("/__/firebase/init.js", () => {
      firebase.analytics();
      router.afterEach(() => {
        firebase.analytics().logEvent("page_view")
      });
    })
  }
}
于 2021-01-04T14:22:36.527 回答