无法从firebase导入auth。

huangapple go评论69阅读模式
英文:

Unable to import auth from firebase

问题

在尝试从 firebase.js 导入 auth 时,我遇到了以下错误:

找不到模块:错误:您尝试导入位于项目 src/ 目录之外的 /firebase/auth。不支持src/之外的相对导入。您可以将其移动到src/内,或从项目的node_modules/目录添加符号链接。

但是 firebase.js 存储在 src 目录中,我一直在尝试导入的文件是 Register.jsx,位于 src/pages 文件夹中。我已经卡在这个问题上好几个小时了。如果能提供任何帮助,将不胜感激。


firebase.js 内容:

import { initializeApp } from "firebase/app";
import { getAuth } from "/firebase/auth";
import { getStorage } from "firebase/storage";

const firebaseConfig = {
  apiKey: "<API_KEY>",
  authDomain: "chateapp.com",
  projectId: "ch715c",
  storageBucket: "chaom",
  messagingSenderId: "4960541",
  appId: "<APP_ID>"
};

// 初始化 Firebase
export const app = initializeApp(firebaseConfig);
export const auth = getAuth();
export const storage = getStorage();

Register.js 内容:

import React from 'react';
import Add from "../img/addAvatar.png";
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { auth, storage } from '../firebase';
import { useState } from 'react';
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";

const Register = () => {
  const [err, setErr] = useState(false);
  const handleSubmit = async (e) => {
    e.preventDefault();
    const displayName = e.target[0].value;
    const email = e.target[1].value;
    const password = e.target[2].value;
    const file = e.target[3].files[0];

    try {
      const res = await createUserWithEmailAndPassword(auth, email, password);

      const metadata = {
        contentType: 'image/jpeg'
      };

      const storageRef = ref(storage, displayName);
      const uploadTask = uploadBytesResumable(storageRef, file, metadata);

      uploadTask.on('state_changed',
        (error) => {
          setErr(true);
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then(async(downloadURL) => {
            await updateProfile(res.user, {
              displayName,
              photoURL: downloadURL,
            });
          });
        }
      );
    }
    catch (err) {
      setErr(true);
    }
  };

  return (
    <div className='formContainer'>
      <div className='formWrapper'>
        <span className='logo'>Lambda Chat</span>
        <span className='title'>Register</span>
        <form onSubmit={handleSubmit}>
          <input type="text" placeholder='display name' />
          <input type="email" placeholder='email' />
          <input type="password" placeholder='password' />
          <input type="file" id='file' style={{ display: 'none' }} />
          <label htmlFor="file">
            <img src={Add} alt="" />
            <span>Add an avatar</span>
          </label>
          <button>Sign Up</button>
          {err && <span>Something went wrong!</span>}
        </form>
        <p>Have an account? Login</p>
      </div>
    </div>
  );
};

export default Register;
英文:

I am getting the following error while trying to import auth from firebase.js

Module not found: Error: You attempted to import /firebase/auth which falls outside of the project src/ 
directory. Relative imports outside of src/ are not supported.
You can either move it inside src/, or add a symlink to it from project&#39;s node_modules/.

However firebase.js is stored in the src directory and the file in which I have been trying to import is Register.jsx which is in the src/pages folder. I have been stuck on this for hours now. Any help would be appreciated.


firebase.js contents

import { initializeApp } from &quot;firebase/app&quot;;
import { getAuth } from &quot;/firebase/auth&quot;;
import { getStorage } from &quot;firebase/storage&quot;;

const firebaseConfig = {
  apiKey: &quot;&lt;API_KEY&gt;&quot;,
  authDomain: &quot;chateapp.com&quot;,
  projectId: &quot;ch715c&quot;,
  storageBucket: &quot;chaom&quot;,
  messagingSenderId: &quot;4960541&quot;,
  appId: &quot;&lt;APP_ID&gt;&quot;
};

// Initialize Firebase
export const app = initializeApp(firebaseConfig);
export const auth = getAuth();
export const storage = getStorage();

Register.js contents

import React from &#39;react&#39;
import Add from &quot;../img/addAvatar.png&quot;
import { createUserWithEmailAndPassword, updateProfile } from &quot;firebase/auth&quot;;
import { auth, storage } from &#39;../firebase&#39;
import { useState } from &#39;react&#39;;
import { ref, uploadBytesResumable, getDownloadURL } from &quot;firebase/storage&quot;;

const Register = () =&gt; {
  const [err, setErr] = useState(false)
  const handleSubmit = async (e) =&gt; {
    e.preventDefault()
    const displayName = e.target[0].value;
    const email = e.target[1].value;
    const password = e.target[2].value;
    const file = e.target[3].files[0];

    try {
      const res = await createUserWithEmailAndPassword(auth, email, password);



      /** @type {any} */
      const metadata = {
        contentType: &#39;image/jpeg&#39;
      };

      const storageRef = ref(storage, displayName);
      const uploadTask = uploadBytesResumable(storageRef, file, metadata);

      uploadTask.on(&#39;state_changed&#39;,
        
        (error) =&gt; {
          setErr(true);
        },
        () =&gt; {
          getDownloadURL(uploadTask.snapshot.ref).then(async(downloadURL) =&gt; {
            await updateProfile(res.user, {
              displayName,
              photoURL:downloadURL,
            });
          });
        }
      );
    }
    catch (err) {
      setErr(true)
    }

  }
  return (
    &lt;div className=&#39;formContainer&#39;&gt;
      &lt;div className=&#39;formWrapper&#39;&gt;
        &lt;span className=&#39;logo&#39;&gt;Lambda Chat&lt;/span&gt;
        &lt;span className=&#39;title&#39;&gt;Register&lt;/span&gt;
        &lt;form onSubmit={handleSubmit}&gt;
          &lt;input type=&quot;text&quot; placeholder=&#39;display name&#39; /&gt;
          &lt;input type=&quot;email&quot; placeholder=&#39;email&#39; /&gt;
          &lt;input type=&quot;password&quot; placeholder=&#39;password&#39; /&gt;
          &lt;input type=&quot;file&quot; id=&#39;file&#39; style={{ display: &#39;none&#39; }} /&gt;
          &lt;label htmlFor=&quot;file&quot;&gt;
            &lt;img src={Add} alt=&quot;&quot; /&gt;
            &lt;span&gt;Add an avatar&lt;/span&gt;
          &lt;/label&gt;
          &lt;button&gt;Sign Up&lt;/button&gt;
          {err &amp;&amp; &lt;span&gt;Something went wrong!&lt;/span&gt;}
        &lt;/form&gt;
        &lt;p&gt;Have an account? Login&lt;/p&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  )
}

export default Register;

答案1

得分: 2

在 firebase.js 中,将 getAuth 导入语句中的初始斜杠 / 删除。

import { getAuth } from "firebase/auth";
英文:

In the firebase.js remove the initial / from the getAuth import.

import { getAuth } from &quot;/firebase/auth&quot;;

To:

import { getAuth } from &quot;firebase/auth&quot;;

huangapple
  • 本文由 发表于 2023年2月10日 16:15:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408459.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定