ukulele
ukulele

Reputation: 87

Getting 'ReferenceError: not defined' when using import/export modules

I've got and exportUserList.js, importUserList.js and the main.js files. The main.js file contains already defined 2 variables which I want to log to the console and I also want to log the imported user variable from the main.js file. But I keep on receiving 'user not defined'. I've used the suggested window option, but it is not passing on the variable. Can this be corrected?

this is the html:

<html lang="en">
   <head>
       <meta charset="utf-8" />
       <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" />
       <title></title>

   <style>
</style>
<head>
</head>
<body>
  <script type="module" src="/importUserList.js"></script>
  <script type="text/javascript" src="/main.js"></script>
       
   </body>

this is the export exportUserList.js :

export const user = 'first user'

this is the import importUserList.js :

import {user} from './exportList.js'

console.log(user)

window.user = user

and this is the main.js:

let names = 'mark'
let numbers = 10

console.log(names)
console.log(numbers)

console.log(user)

Upvotes: 0

Views: 2519

Answers (1)

Option 1: defer your main script, because modules defer by default, and so because your main script doesn't it gets runs before the module has.

However, that's the bad option, and you shouldn't put that into practice because that keeps you using modules in completely the wrong way. Never do that.

The much better solution is to make your main.js a module and then tell it to import what it needs in order to run. You don't load modules only to bind their data onto globalThis (window in this case), the whole point of modules is to keep code contained, so that whatever needs a module's exports, can just import that as needed. You use modules to not pollute the global scope =)

So: remove that importUserList.js and instead put the import in your main script:

import {user} from './exportList.js'

let names = 'mark'
let numbers = 10

console.log(names)
console.log(numbers)
console.log(user)

And then load your main script as a module with:

<script type="module" src="/main.js"></script>

And then of course remember that modules always load deferred.

Basically: if you're using modules, use modules "all the way down".

Upvotes: 2

Related Questions