0

I am trying to create a login system using Firebase authentication and I am running into several errors. After following Google's tutorial (https://www.youtube.com/watch?v=rQvOAnNvcNQ) and creating a simple "Index.html" & "Index.js" test, I received the error "Uncaught SyntaxError: Cannot use import statement outside a module index.js:1". I can change the .js to a .mjs and read it in as a module, but then the .html file cannot find the functions in the .mjs file.

onAuthStateChanged() logs "No user", so I know that's working.

I've been testing via localhost if that makes any difference.

Any help would be greatly appreciated!

index.mjs

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js';
import { getAuth, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js';

const firebaseConfig = {
  ...
};

const app = initializeApp(firebaseConfig);

const auth = getAuth(app);

onAuthStateChanged(auth, (user) => {
  if (user) {
    console.log('logged in!');
  } else {
    console.log('No user');
  }
});


function login() {
  window.alert("Login successful")
}

function signUp() {
  window.alert("Signup successful");
}

index.html

<!DOCTYPE html>
<html lang = "en-US">

<head>
  <meta charset = "UTF-8">
  <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
  <title> test </title>
  <script type="module" src="/index.mjs"></script>
</head>
  <body>
    <div class = "login-form">
        <input type = "email" class="login-username" id="login-username" autofocus="true" required="true" placeholder="Email" />
        <input type = "password" class="login-password" id="login-password" required="true" placeholder="Password" />
        <input type = "submit" name="Login" value="Login" class="login-submit" onclick = "login()"/>
        <input type = "submit" name="Signup" value="Signup" class="login-submit" onclick = "signUp()"/>
    </div>
  </body>
</html>
Andrew Sides
  • 71
  • 1
  • 1
  • 3

1 Answers1

0

It's a case-specific situation. Probably more information will help. But meanwhile, try using the "require" way rather than the import one.

refer to this link as it has a solution for the problem you might be facing.

Himadhar H
  • 106
  • 9
  • Please read that again he is doing everything in vanilla js and he can't use `require` and he mentioned that `import` works for him only problem is cannot access functions defined in js from html – Jack Sep 15 '21 at 06:55
  • Pretty sure he is working on vanillajs because I read it too :) Please read my answer as it has a link for people facing similar issues. But rather polishing the dependencies to build via bundler to handle this, and there are people who have answered that – Himadhar H Sep 15 '21 at 07:21