Modules, importing and exporting
// user.js
exports . name = "John" ;
// ------------------------------------------------
// main.js
const { name } = require ( "./user" ) ;
console . log ( "Name: " , name ) ; // Name: John
// 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
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
// 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] "}
// 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