I am just beginning to learn ES6 imports, with the hopes to transition an application to modular ES6. My current project has the following directory structure:
index.html
-scripts\
--function1.js
--function2.js
--globals.js
--main.js
My index.html file code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Modular JS Example</title>
</head>
<body>
<button onclick="changevar1()">Change Var 1</button>
<button onclick="changevar2()">Change Var 2</button>
<script src="scripts/main.js" type="module"></script>
</body>
</html>
As you can see, I have two buttons which have onclick
triggers assigned to them. These functions namely, changevar1()
and changevar2()
are found in files function1.js
and function2.js
respectively. And my entry point is main.js
.
My main.js is as follows:
import {globalvar1 as globalvar1,
globalvar2 as globalvar2} from "./globals.js";
import {changevar1 as changevar1} from "./function1.js";
import {changevar2 as changevar2} from "./function2.js";
console.log(globalvar1, globalvar2,changevar1,changevar2);
My globals.js is where I declare some global variables which will be used by functions in either functions1.js
or functions2.js
and is as follows:
export let globalvar1 = "I am globalvar1";
export let globalvar2 = "I am globalvar2";
My function1.js has the function for the first button and is as follows:
import { globalvar1 } from "./globals.js" //do I need to import here?
export function changevar1() {
globalvar1 = "Now changed globalvar1"
console.log(globalvar1);
}
In the case above, I am importing the globalvar1
from globals.js
and I am not sure if that is required, or if it will all come together in main.js
?
My function2.js has the function for the second button and is as follows:
export function changevar2() {
globalvar2 = "Now changed globalvar2"
console.log(globalvar2);
}
In this case, I was not importing the globalvar2
, just to see if it was not required.
Now the question is simply when you press the button how can you trigger either changevar1()
or changevar2()
to change the globalvar1
or globalvar2
? I keep getting "Reference errors".
I have read several online documents and watched a few video tutorials online too to try to understand modular js. Please excuse my lack of knowledge about modules and any help even if very basic knowledge is helpful.