Skip to content

Instantly share code, notes, and snippets.

@akulsr0
Created June 5, 2022 11:22
Show Gist options
  • Save akulsr0/00be91dd4db2b1dba1bd610e890ee771 to your computer and use it in GitHub Desktop.
Save akulsr0/00be91dd4db2b1dba1bd610e890ee771 to your computer and use it in GitHub Desktop.

Modules, importing and exporting

CommonJS

Exporting a variable

// user.js
exports.name = "John";

// ------------------------------------------------

// main.js
const { name } = require("./user");

console.log("Name: ", name); // Name: John

Default Exporting

// user.js
const name = "John";
const age = 25;

module.exports = {
  name,
  age,
};

// ------------------------------------------------

// main.js
const user = require("./user");

console.log("Name: ", user.name); // Name: John
console.log("Age: ", user.age); // Age: 25

ES6

Exporting a variable/function etc...

// user.js
export const name = "John";

export function add(a, b) {
  return a + b;
}

// ----------------------------------------

// main.js
import { name, add } from "./user";

console.log("Name: ", name); // Name: John
console.log("Sum: ", add(1, 2)); // Sum: 3

Default Exporting

// user.js
export default {
  name: "John",
  age: 25,
  email: "[email protected]",
};

// ------------------------------------------------

// main.js
import user from "./user";

console.log(user); // {name: "John", age: 25, email: "[email protected]"}

// ------------------------------------------------

// main.js
import { default as user } from "./user";

console.log(user); // {name: "John", age: 25, email: "[email protected]"}

Combined

// user.js
export const name = "John";

export default {
  name,
  email: `${name}@fakeuser.in`,
  phone: "9998887770",
};

// ------------------------------------------------------------

// main.js
import user, { name, email, phone } from "./user";

console.log("Name: ", name); // Name: John
console.log("Email: ", email); // Email: undefined
console.log("Phone: ", phone); // Phone: undefined

console.log("UserEmail: ", user.email); // UserEmail: [email protected]
console.log("UserPhone: ", user.phone); // UserPhone: 9998887770
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment