Access variables declared in dynamically imported JavaScript?

橙三吉。 提交于 2020-05-29 10:52:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!