Assembly in Progress...

Modules in JavaScript

JS Modules allow for the grouping of code to contain variables while making the sharing of properties easier.

Modules can be brought in like this:
import module1 from 'module1';
export function jump() {
    ...code
}

↓ Examples ↓

 //    The following would be in a file named force-duel.js in the 'modules' folder inside the 'js' folder        
 const anakin = {
     name: 'Anakin',
     power: 10
 }
 const dooku = {
     name: 'Count Dooku',
     power: 7
 }
 export function fight(char1, char2) {
     const attack1 = Math.floor(Math.random() * char1.power);
     const attack2 = Math.floor(Math.random() * char2.power);
     return attack1 > attack2 ? `${char1.name} wins` : `${char2.name} wins`
 }


 //    The following would be in the main script.js (or any other JS)
 import {
     fight
 } from 'js/modules/force-duel.js';

 //    now you can call the imported function
 console.log(fight(char1, char2));


 //    If you are importing to the main index.html, you need to specify type = "module"

<script type = "module" >
 import {
     fight
 } from 'modules/force-duel.js';

 //    now you can call the imported function
 console.log(fight(char1, char2));
 </script>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

q
↑ Back to Top