From a4c292be04ab816218bf81433d5ba473693a799e Mon Sep 17 00:00:00 2001 From: KOD3X Date: Thu, 3 Mar 2022 13:45:06 +0100 Subject: [PATCH] Clarify exports and imports When exporting or importing you must take into account the context, since it is not the same to export or import in javascript for node.js than for native javascript. I think the user must understand when an export or a module.exports is used. On the other hand, including the call from the html will help a lot to test the example. I hope to be of help. --- javascript.md | 76 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 45 insertions(+), 31 deletions(-) diff --git a/javascript.md b/javascript.md index 3cbddf0..a9e5476 100644 --- a/javascript.md +++ b/javascript.md @@ -1121,6 +1121,51 @@ JavaScript Modules {.cols-2} ------------ +### Export + +```javascript +// myMath.js + +// Default export +export default function add(x,y){ + return x + y +} + +// Normal export +export function multiply(x,y){ + return x * y +} + +// Multiple exports +function subtract(x,y){ + return x - y +} +function duplicate(x){ + return x * 2 +} +export { + subtract, + duplicate +} +``` + + +### Import keyword + +```javascript +// main.js +import add, { multiply, subtract, duplicate } from './myMath.js'; + +console.log(multiply(6, 2)); // 12 +console.log(add(6, 2)); // 8 +console.log(subtract(6, 2)) // 4 +console.log(duplicate(5)) // 10 + +// index.html + +``` + + ### Require ```javascript @@ -1135,21 +1180,6 @@ console.log(moduleA.someFunctionality) ``` -### Export - -```javascript -// module "moduleA.js" -export default function cube(x) { - return x * x * x; -} - -// In main.js -import cube from './moduleA.js'; -// Now the `cube` function can be used straightforwardly. -console.log(cube(3)); // 27 -``` - - ### Export Module ```javascript @@ -1159,22 +1189,6 @@ module.exports = Course; ``` -### Import keyword - -```javascript -// add.js -export const add = (x, y) => { - return x + y -} - - -// main.js -import { add } from './add'; -console.log(add(2, 3)); // 5 -``` - - - JavaScript Promises {.cols-2} ------------