csguy
csguy

Reputation: 1474

Re Export Statement Difference (Javascript)

Difference between export {sayHi} from ‘./say.js’ and export {default as sayHi} from ‘./say.js’?

Doesn't the first statement rename default to sayHi just like the second one?

Also are these statements valid? If not why?

Upvotes: 1

Views: 72

Answers (1)

sonEtLumiere
sonEtLumiere

Reputation: 4562

I hope this helps. There are many ways to export/import in JS, maybe this answer is too teorical but this is my reference to understand how modules works in JS.

//MODULES

module.exports  //exports the module for use in another program.
require()       //imports the module for use in the current program.


//exports / require
//exports   (in menu.js file).
let Menu = {};      //Create an object to represent the module.
Menu.specialty = "Roasted Beet Burger with Mint Sauce";     //Add properties or methods to the module object.
module.exports = Menu;  //Export the module with module.exports.
//require   (in order.js file).
const Menu = require('./menu.js');  //Import the module with require() and assign it to a local variable (the .js extension is optional).
console.log('My order is: ' + Menu.specialty);  // Use the module and its properties within a program.


//export default
let Menu = {};
export default Menu;   //Uses the JavaScript export statement to export JavaScript objects, functions, and primitive data types.
//import
import Menu from './menu';


//Named exports
let burger = 'test';
export { burger };  //Named exports allow us to export data through the use of variables.
//Named imports
import { burger } from './menu';


//Export named exports
export let fries = "fries"; //They can be exported as soon as they are declared
//Import named imports
import { fries } from 'menu';


//Export assign                 
let specialty = "specialty";
export { specialty as chefsSpecial };   // The 'as' keyword allows us to give a variable name.
//Import as
import { chefsSpecial as specialForYou } from 'Menu';


//Another way of using aliases is to import the entire module as an alias:
import * as Carte from './menu';
Carte.chefsSpecial;
Carte.isVeg();
Carte.isLowSodium(); 

Upvotes: 1

Related Questions