Skip to content

Instantly share code, notes, and snippets.

@MorganConrad
Created January 17, 2018 00:06
Show Gist options
  • Save MorganConrad/3110756b01a9429ee26e81a16015bd12 to your computer and use it in GitHub Desktop.
Save MorganConrad/3110756b01a9429ee26e81a16015bd12 to your computer and use it in GitHub Desktop.
ES6 Import
import {add, subtract} from './modules/supermath.js';
window.glue = {
doMath :function doSomething1(ida, idb, idop, idresult) {
let a = Number(document.getElementById(ida).value);
let b = Number(document.getElementById(idb).value);
let op = document.getElementById(idop).value;
let result = (op === '+') ? add(a,b) : subtract(a,b);
document.getElementById(idresult).value = result;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>Test</title>
<script type="module" src="./glue.js"></script>
</head>
<body>
<header>
</header>
<main>
<h1> Import Test </h1>
<input type="number" id="a"></input>
<select id="op">
<option value="+">+</option>
<option value="-">-</option>
</select>
<input type="number" id="b"></input>
<button id="doit" onclick="window.glue.doMath('a','b','op','result')">=</button>
<textarea id="result" rows="1" readonly></textarea>
</main>
</body>
</html>
export function add(a,b) {
return a+b;
}
export function subtract(a,b) {
return a-b;
}
@MorganConrad
Copy link
Author

ES6 Import Demo

This is a short demo of how to do an ES6 import in the browser.

supermath.js

This represents some general-purpose module or utility code, usable in a variety of situations. Something you might find on GitHub or npmjs. As such, it has no specific DOM stuff, even any React, jQuery, etc., though YMMV. It should be placed into a "modules" folder under the index.html and glue.js files. In this example it exports two functions.

index.html

The web page that (eventually) uses the supermath module. It does so by using the script glue.js, which must be of type="module".

glue.js

  • glues our specific code (DOM) to the underlying supermath module.
  • imports the functions add and subtract exposed by supermath.js
  • "exposes" it's own function, doMath().
    • Unlike a normal script, it cannot just declaredoMath() as a global
    • So it adds doMath() to window, using the namespace window.glue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment