问题
I am working on Single Page Architecture (SPA) Web application. I am have implemented functionality to dynamically load different pages of application.
This is what my spa.js looks like
var spa = {
init: async () => {
await import('./page.js')
spa.data['page'].apply()
},
register: (page, data) => {
spa.data[page] = data
},
data: {},
}
window.onload = () => {
spa.init()
}
And this is what my page.js looks like
const pageData = {
apply: () => {
document.body.innerHTML = getMSG()
}
}
function getMSG() {
return "hello message!"
}
spa.register('page', pageData)
The working process explained:
- Initially spa.js loads. spa.data is empty
- It initiates spa.init(), which loads page.js
- page.js registers its data to spa variable
- Now control jumps back at spa.js and from spa.data for page, it will execute apply()
This works fine. But here's a strange thing!
The apply() method has access to bare getMSG(), but when I try to execute getMSG() it via browser's developer console I get ReferenceError implying that getMSG() is not defined at all! Same goes with our pageData
Here is the hosted heroku app, you can try - dyn-import
Although it is very good as I don't have to worry about clashing functions in different files, I want to know how this is happening.
Can someone explain how can I access methods and variables defined in page.js. I am aware about exports, but it is somehow possible without exports!
回答1:
You cannot directly access functions and variables defined in the module if they are not exported.
Reason why spa
variable is accessible globally is because spa.js
is normal script, referenced in the HTML document head.
<head>
...
<script src="./spa.js"></script>
</head>
If you, on the other hand, import
script, variables are in different scope, unless you export them. So page.js
is treated as a module.
You could, of course, attach function getMSG()
to the global spa
variable, or pageData
, but both would be workarounds.
spa.getMSG = getMSG;
You can read more about differences between modules and standard scripts here - MDN JavaScript modules.
来源:https://stackoverflow.com/questions/61892074/access-variables-declared-in-dynamically-imported-javascript