CMPUT 404

Web Applications and Architecture

More JavaScript

Created by
Hazel Campbell (hazel.campbell@ualberta.ca).
Copyright 2023.

Modules

  • At some point it became necessary to split JS into multiple files.
  • Originally you'd just use multiple <script> tags
  • 2009: CommonJS modules
  • 2016: ES modules (aka ES6 modules)

CommonJS modules

'use strict';
module.exports.safeAdd = function(a, b) {
    const s = a + b;
    if (Number.isSafeInteger(s) && Number.isSafeInteger(a) && Number.isSafeInteger(b)) {
        return s;
    } else {
        throw Error("Numbers got too big!");
    }
}
module.exports.safeSubtract = function(a, b) {
    const s = a - b;
    if (Number.isSafeInteger(s) && Number.isSafeInteger(a) && Number.isSafeInteger(b)) {
        return s;
    } else {
        throw Error("Numbers got too big!");
    }
}

CommonJS modules

safety.js

'use strict';
const safeAdd = function(a, b) {
    // some code ...
}
const safeSubtract = function(a, b) {
    // some code ...
}
module.exports = { safeAdd, safeSubtract };

something else in the same folder...

'use strict';
const {safeAdd, safeSubtract} = require('./safety'); // note no .js
console.log(safeAdd(2, 2));

ES Modules

safety.mjs

// don't need use strict, its on by default in ES modules! 
export function safeAdd(a, b) {
    // some code ...
}
export function safeSubtract(a, b) {
    // some code ...
}

something else in the same folder...

import {safeAdd, safeSubtract} from './safety.mjs'; // we do need the .mjs here
console.log(safeAdd(2, 2));

ES Modules

Async loading...

async function loadAndSubtract() {
    safety = await import("./safety.mjs");
    console.log(safety.safeAdd(2, 2));   
}

Modules

  • use .mjs to tell Node and other libraries that it's an ES Module.
  • use .esm or .esm.js are ES modules, but not recognized by Node.
  • use .cjs to tell Node and other libraries that it's an CommonJS Module (rare).
  • Both support full URLs, though if you're not using relative URLs you're setting yourself up for a security problem.

CommonJS Modules

  • Frontend code that uses CommonJS
    • Needs library or bundler (RequireJS, Webpack, etc.) to work in browser.

ES Modules

  • Needs Node.js version 14 or better, supported natively in browser.
  • You can use "top-level await" that is, await outside of an async function
    • This delays loading until the promise resolves

Transpilers & Bundlers

  • Examples:
      webpack (+babel)
      rollup
      esbuild
      ...

Transpilers & Bundlers

  • Make JS load faster (maybe) by merging large trees of modules into single files
    • Also can combine CSS, image files, etc. into JavaScript
  • Support more modern features on older browsers
    • Original purpose of Babel was to compile ES6 to ES5
  • Compile a variety of languages (TypeScript, CoffeeScript...) to JavaScript

Transpilers & Bundlers

  • Avoid hosting your entire node_modules
    • Scans for dependencies
  • Automatically add hashes to files for cache-busting
  • Interferes with debugging

Tree Shaking

  • Bundlers usually perform Tree-Shaking
  • Removing unused parts of modules and their dependencies
  • The previous example only used safeAdd and safeSubtract, so all other exports would be removed

Polyfills

  • Bundlers often also automatically add polyfills
  • JS script that adds support for newer features not supported in older browers
  • Different from a transpiler!
    • Transpiler: runs before deployment during build
    • Polyfill: runs in the browser at runtime

Polyfills vs Transpilers

  • Example:
    • Require.js is a polyfill for CommonJS module support
    • rollup-plugin-commonjs transpiles CommonJS to ES Modules at build time

Debugging Transpiled/Bundled Frontents

  • Source maps!
  • Like debugging symbols gcc -g, but for the web
  • Produced to map the output html/css/js from transpilers, bundlers, minifiers, and templaters to the original source code
  • //# sourceMappingURL=yourFileName.min.js.map
  • Not perfect
  • So far only supports JS and CSS

Spread operator

  • ...
  • When used in arguments: takes an array and turns it into arguments
  • When used in parameters: takes the rest of the arguments passed in and turns it into an array
  • When used in an array: takes an array and inserts its contents into the array

Spread operator

const f = (...a) => {
    // a is an array of all the arguments passed in
    console.log(...a); // give console.log multiple arguments 
    const b = [0, ...a]; // b is a new array with 0, then the elements from a
    console.log(...b);
}
f(1, 2, 3) // works just like console.log(1, 2, 3)

License

Copyright 2014-2023 ⓒ Abram Hindle

Copyright 2019-2023 ⓒ Hazel Victoria Campbell and contributors

Creative Commons Licence
The textual components and original images of this slide deck are placed under the Creative Commons is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Other images used under fair use and copyright their copyright holders.

License


Copyright (C) 2019-2023 Hazel Victoria Campbell
Copyright (C) 2014-2023 Abram Hindle and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN.

01234567890123456789012345678901234567890123456789012345678901234567890123456789