JavaScript Write Tree Shaking Friendly Modules (ECMAScript)

Apr 13, 2022

CommonJS modules usually involves module.exports and require.

ECMAScript/ES2015/ES6 modules usually involve export and import.

NOTE: I believe ECMAScript/ES6 is better for size optimization / tree-shaking as compared to CommonJS, but I might be wrong.

Sample ECMAScript/ES6 modules: ~/libs/client.js

// import RelativeTime from '@yaireo/relative-time'export function simpleSlugify(str) {  return str.toLowerCase()    .replace(/\s+/g, '-')           // Replace spaces with -    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars    .replace(/\-\-+/g, '-')         // Replace multiple - with single -    .replace(/^-+/, '')             // Trim - from start of text    .replace(/-+$/, '');            // Trim - from end of text}export function isMobile() {  if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))    return true  return false}export function ago(date) {  // I am not sure if this approach will work well (or made it worse)  const RelativeTime = require('@yaireo/relative-time')  const relativeTime = new RelativeTime();  return relativeTime.from(date)}export default {  simpleSlugify, isMobile, ago}

How to import

import { extractDomain } from '~/libs/client'

NOTE: I am using Nuxt, which uses Webpack for tree-shaking.

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.