如何在Vuepress中添加Firebase?

时间:2018-10-29 22:28:21

标签: firebase 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>

```

2 个答案:

答案 0 :(得分:0)

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

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

我的回答还包括启用 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")
      });
    })
  }
}

答案 1 :(得分:-1)

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

请注意,我也在这里同时初始化firebasefirestore。因此,我将firestore作为全局变量。

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

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