如何将 firebase 添加到 Vuepress?

How to add firebase to Vuepress?

我正在尝试将 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>

```

head 数组的 config.js 中添加类似的内容。请注意,这会添加 firebase-app(核心)、firebase-authfirestorecloud functions,因为我在我的项目中使用了 4 个模块。

请注意,我也在此处初始化 firebasefirestore。所以我将 firestore 作为全局变量。

当 firebase 加载时,所有这些都将被提升到应用程序的头部。

 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);`
    ],
    ]

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

Google 转移到更通用的配置模型。它建议使用 include 自动获取配置参数。

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

config.jshead数组中:

    ["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")
      });
    })
  }
}