Skip to content

Instantly share code, notes, and snippets.

@vhbui02
Last active May 9, 2023 08:49
Show Gist options
  • Save vhbui02/b1b62494d7c166050c2f437db3bd5533 to your computer and use it in GitHub Desktop.
Save vhbui02/b1b62494d7c166050c2f437db3bd5533 to your computer and use it in GitHub Desktop.
[import/export in CJS vs ES6] the last time i'm gonna forget about this #js

CommonJS Syntax (CJS for short)

Module system used in Node.js and other JavaScript environments.

Importing

const moduleA = require('./moduleA'))
const [moduleA, moduleB, moduleC] = require([
	'./moduleA',
   './moduleB',
   './moduleC'
])

Exporting

module.exports = {
	someFunc: () => {
   	console.log('Hello World!')
   }
}
module.exports = {
	moduleA,
  	moduleB,
  	moduleC
}

ECMAScript6 (ES6)

Newer module system introduced in modern JS environments.

Importing

// Importing single module:
import { moduleA } from './moduleA'
// Importing multiple modules:
import { moduleA, moduleB, moduleC } from './modules'
// Renaming imports
import { modules as A, moduleB as B } from './modules'

Exporting

Named export

in the source.js file, export the desired variables, functions, classes that thave a specific name

// File: source.js
export const myVariable = /* */
export function myFunction() { /* */ }
export const myFunctionArrowExp = () => { /* */ }
export class myClass { /* */ }
export { myVariable, myFunction, myClass }

Access the above item in the target.js file:

// file: target.js
import { myVariable } from "./source.js"
import { myFunction } from "./source.js"
import { myClass } from "./source.js"

Default export: USE ONLY ONCE in each .js file

Actually, each .js file can have "multiple named exports" and "only one default export".

// file: source.js
export default function myNewFunction() { /* */ }

With this, when importing in the target.js file, JS understands which item is exported as default.

// file: target.js
import anyNameWillDo from "./source.js"

***NOTE: Unlike named exports, in default export we don't need to export named items and we can export "unnamed items" as well. They are anonymous functions and classes, as well as expressions and object literals. ***

E.g. Export an object literals:

export default {
	myFunc: () => console.log('Hello World!'),
  	myVar: 'abc'
}

Some special export feature

// exporting aliases
export { moduleA as A, moduleB as B } from './modules'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment