Module system used in Node.js and other JavaScript environments.
const moduleA = require('./moduleA'))
const [moduleA, moduleB, moduleC] = require([
'./moduleA',
'./moduleB',
'./moduleC'
])
module.exports = {
someFunc: () => {
console.log('Hello World!')
}
}
module.exports = {
moduleA,
moduleB,
moduleC
}
Newer module system introduced in modern JS environments.
// 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'
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'
}
// exporting aliases
export { moduleA as A, moduleB as B } from './modules'