Home > Net >  JS wont access const between scripts
JS wont access const between scripts

Time:05-26

It seems very simple but it wont work. I just want to access auth variable between index.js and auth.js but it keeps giving me error that auth is not defined in auth.js. I thought if i put the script for index.js above auth.js i would be able to use its variables in auth.js. It should be known that this all works correctly when placed in same file.

index.html :

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, intial-scale=1.0"/>
<title>yuh</title>

</head>
<body>
yo


<form id="signup-form">
  <input type="email" id="signup-email"/>
  <input type="password" id="signup-password"/>  
<button>Submit</button>

</form>

<script type="module" src="index.js"></script>
<script type="module" src="auth.js"></script>

</body>


</html>

index.js:

import { getAuth, createUserWithEmailAndPassword  } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-auth.js";
import { getFirestore} from "https://www.gstatic.com/firebasejs/9.8.1/firebase-firestore.js";

const firebaseConfig = {
    apiKey: "Afirebase crapYw",
    authDomain: "firebase crap",
    databaseURL: "https://firebase crap.firebaseio.com",
    projectId: "firebase crap",
    storageBucket: "firebase crap.appspot.com"
   
  };

  const app = initializeApp(firebaseConfig); 
  const auth = getAuth(app);
  const db = getFirestore(app);

auth.js:

signupForm.addEventListener('submit', (e) => {
e.preventDefault();

const email = signupForm['signup-email'].value;
const password = signupForm['signup-password'].value;

console.log(email, password);
auth.createUserWithEmailAndPassword(email, password).then((cred) => {

  const user = cred.user;
}).catch((error) => {
  const errorCode = error.code;
  const errorMessage = error.errorMessage;
});



});

CodePudding user response:

You can use window.<YourVariableName> = <Value>

For Example

window.auth = getAuth(app);

CodePudding user response:

You should export your const auth.

index.js

...

export const app = initializeApp(firebaseConfig); 
export const auth = getAuth(app);
export const db = getFirestore(app);

...

auth.js

import { auth } from 'path/to/index.js';

auth //now accessible!

  • Related