I've been developing a javascript application the old fashion way. That is, by referencing scripts one after the other in the html page header:
<head>
...
<script src="./helpers.js"></script>
<script src="./pwvlogic.js"></script>
</head>
But I would like to treat helpers.js as a module and import it into pwvlogic.js, and then remove the reference to it from the html page.
Here's what helpers.js looked like before the change:
function createLineDiv(line) {
...
}
function fillActionButtonsContainer(actionButtonsContainer, line) {
...
}
function highlightSearchString(content) {
...
}
And here's what it looks like after the change:
export function createLineDiv(line) {
...
}
export function fillActionButtonsContainer(actionButtonsContainer, line) {
...
}
export function highlightSearchString(content) {
...
}
export default {
createLineDiv,
fillActionButtonsContainer,
highlightSearchString
}
And in pwvlogic.js, I add an import statement at the top:
import { createLineDiv, fillActionButtonsContainer, highlightSearchString } from './helpers.js';
Then in the html file, I remove the reference to helpers.js and add type="module"
to the pwvlogic.js reference:
<script src="./pwvlogic.js" type="module"></script>
Now there is an issue with loading the pageLoad() function. In my html, I have this:
<body onload="pageLoad()">
And in pwvlogic.js, I have the pageLoad
function:
function pageLoad() {
...
}
In the browser, I get the error:
Uncaught ReferenceError: pageLoad is not defined
Why is pageLoad
suddenly undefined? Can I not reference it in a javascript module the same way I can a regular javascript file? How do I fix this?
Thanks!
pageLoad()
is scoped to its module, it's not a property of global object. You might need to make it a property of window
if you want to use it in regular js
<body onload="hello()">
<script type="module">
function hello() {
console.log("hello")
}
window.hello = hello
</script>
</body>