首页 > 解决方案 > 重新出口声明差异(Javascript)

问题描述

标签: javascript

解决方案


我希望这有帮助。在 JS 中导出/导入的方法有很多,也许这个答案太冗长了,但这是我了解模块在 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(); 


推荐阅读