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: