简体   繁体   中英

Exportin/importing javascript modules

Nooby question: I've got file main.js with module let myModule = {} , defined there inside $(document).ready(function() . And I have another file summary.js where I would like to use it. I declare them all in the head of html file:

<script src="js/main.js"></script>
<script src="js/summary.js"></script>

I would like to use myModule module in the summary.js file and extend it. So I would like to be able to define: myModule.summary = {}. For now I receive the error myModule is undefined even though all js files are uploaded correctly (I can see them in debugger in dev console of the browser). I expect I have to export the mdrx module somehow but export default mdrx at the end of main.js does not do the job. How to do it correctly? I read the documentation but it seems like structural problem as I couldn't figure that out. Can that be that the myModule is not loaded yet before loding summary.js? If so how to prevent that?

You can use the type attribute to achieve this:

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

Then you can import the module in other JavaScript files:

import yourModule from './main.js'

The problem was that the whole myModule was defined inside function() (called within document.ready event). Moving it outside that solved the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM