To make objects,functions,classes or variables available to the outside world it's as simple as
exporting them and then importing them where needed in other files.
1.Import default exports
import carTires from './autoParts/tires.js';
2.Import default export and additional functions
import carTires, { ShineTires } from './autoParts/tires.js';
3.Import a default export plus all the other exports in a file.
import carTires, * as tireOptions from './autoParts/tires.js';
Note : This is known as namespace import.
If you'r importing a default export along with named or namespace imports, be aware that the default export will have to be declared first.
4.A single export from a module : named import
import { apples } from './plants/fruits.js';
5.Multiple exports from a single module :
import { carrots, potatoes, onions } from './plants/veggies.js';
6.Alias an import with a more convenient name :
import { mySuperCaliFragilisticExpialidociusObject as mySuperObject } from './maryPoppins.js';
7.Rename multiple exports during import :
import { ladyMaryCrawley as ladyMary, ladyEdithCrawley as ladyEdith, ladyCoraCrawley as ladyGrantham } from './downtonAbbeyFamily/ladies.js';
Just like renaming one export,you can rename multiple exports on import.
8.Dynamic imports or import() operator :
Dynamically importing ES modules with import() operator.
with import() operator we can load modules dynamically .
ex : const myModule='./myModules.js';
import(myModule)
.then(x => x.someMethod());
1. we can load some modules on demand.
2. we can load some modules depending on whether a condition is true.
The 'import' keyword may be called as a function to dynamically import a module.when used this way,it returns a promise.
ex: dynamic imports with promise syntax
import ('./waysToTravel.js')
.then((vehicles) => {
// do something with planes, trains and automobiles
});
ex: dynamic imports with async/await syntax
let vehicles = await import('./waysToTravel.js');
Exports :
1.Default Export
ex :
export const myNumbers = [1, 2, 3, 4];
const animals = ['Panda', 'Bear', 'Eagle'];
export default function myLogger() {
console.log(myNumbers, pets);
}
Note: Each Javascript file can only have one default export.
All other export in that same file will just have the 'export' keyword in front of them.
2.Individual named exports
ex :
export const myPets = [ "dog", "cat", "guinea pig", "gold fish"];
const mySecretPets = [ "dragon", "griffin", "Loch Ness monster", "Big Foot"];
export function nameMyPets() {
console.log(myPets, mySecretPets)
}
named import syntax:
import { myPets, nameMyPets } from './pets.js';
3.Multiple named export in a single line
export { cakes, cookies, makeDessert, makeTea };
4.Exporting with aliases
ex : export { myNumbers, myLogger as Logger, Alligator }
No comments:
Post a Comment