【问题标题】:What's the best way to run some code only client side?仅在客户端运行某些代码的最佳方法是什么?
【发布时间】:2019-11-09 03:42:15
【问题描述】:

我正在尝试在 Sapper 中实现 firebase。 我安装了模块(@firebase/app、@firebase/auth、@firebase/firestore),然后编写了一个配置文件:

import firebase from '@firebase/app';
import '@firebase/firestore'
import '@firebase/auth'

const config = {
...
};

// Initialize Firebase
firebase.initializeApp(config);
export { firebase };
// Initialize db
export const db = firebase.firestore();
export const auth = firebase.auth();

当我“npm run dev”时,我收到一条错误消息,指出这些 firebase 模块仅适用于客户端,而不适用于 Node.js。

因此,我尝试通过多种方式解决此问题,目前唯一可行的方法是使用 onMount。

  onMount(async () => {
    const {auth} = await import('../firebase/config');
    auth.signInWithEmailAndPassword("test@gmail.com", "test").then((res) => {
      // do some stuff
    })
  })

现在可以了,但我有 3 个问题:

1) 这是正确的方法吗? 2)我应该从服务器端删除这些模块还是更好地保留它们? 3) 我应该同时使用客户端和服务器端版本的 firebase,并使用客户端一个来检索每个访问者和服务器端与所有公共数据不同的所有数据吗?

【问题讨论】:

    标签: svelte sapper


    【解决方案1】:

    我会检查process.browser

      onMount(async () => {
        if (process.browser) {
          const {auth} = await import('../firebase/config');
          auth.signInWithEmailAndPassword("test@gmail.com", "test").then((res) => {
            // do some stuff
          })
        }
      })
    

    if (process.browser) {
      onMount(async () => {
        const {auth} = await import('../firebase/config');
        auth.signInWithEmailAndPassword("test@gmail.com", "test").then((res) => {
          // do some stuff
        })
      })
    }
    

    【讨论】:

      【解决方案2】:

      我想说你很接近,但你可以将导入排除在 onMount 回调之外:

      <script>
      import { auth } from '../firebase/config';
      import { onMount } from 'svelte'
      
      onMount(() => {
          auth.signInWithEmailAndPassword("test@gmail.com", "test").then((res) => {
            // do some stuff
          })
      })
      </script>
      

      如果您这样做,您的 firebase 代码将不会在 SSR 期间被调用,并且您不必处理异步模块加载。

      话虽如此,我认为将您的 firebase 代码放在服务器路由中,并从客户端调用该路由可能是一种更清洁、更有效的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-14
        相关资源
        最近更新 更多