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:
↓ Examples ↓import module1 from 'module1';
export function jump() {
...code
}
// 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>
Page Navigation
q