General Questions About Modules

  1. Is it standard practice to use only one module <script type="module"> per external file? For example, say I have a file modules.js with several different blocks of <script type="module">, and in my main index.js file I append <script type="module" src="modules.js", will it import all the different blocks from the modules.js file? Is this improper practice?

  2. I read that if a module is exported multiple times, it will only run its code on the first import. Does that mean that the second receiving file can’t call functions from the imported <script>?

  3. In order to import an entire module, do we have to give any kind of export command in that module, or do we simply append <script type="module src="modules.js" into the destination <script>?

A module is a file with one or more import and/or export declarations in it, if it doesn’t have either of those it’s a script, not a module.

It caches the code (otherwise the browser would be storing multiple versions of the same thing), but that cached code can be used in multiple different places. Essentially, you get an object with some properties/functions attached to it when you omport something, same as any JS it can be used in multiple places.

You’d often just have one main file (module) referenced in the HTML, and that kicks everything off, imports the bits you need, exported from other JS files, which import from other ones etc. Context sensitive (you can have as many script tags as you want in an HTML file), but it normally keeps things sane having a single entry point.

2 Likes

Thank you so much for the detailed explanations, @camperextraordinaire and @DanCouper. I frequently see your guys’ posts. This was my first time hearing from Randell. Dan actually answered one of my previous questions about Decorators and Forwarding. FCC is such a great community. Have a great weekend, guys.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.