JavaScript Tutorial - 13 - Module Export/Import
INTERMEDIATE JAVASCRIPT MODULES
|| --Hello Modules-- ||
JavaScript modules are reusable pieces of code that can be exported from one program and imported for use in another program.
Modules are particularly useful for a number of reasons. By separating code with similar logic into files called modules, we can:
• find, fix, and debug code more easily;
• reuse and recycle defined logic in different parts of our application;
• keep information private and protected from other modules;
• and, importantly, prevent pollution of the global namespace and potential naming collisions, by cautiously selecting variables and behavior we load into a program.
we’ll cover two ways to implement modules in JavaScript: Node.js’s module.exports and require() syntax, as well as the ES6 import/export syntax.
|| --module.exports-- ||
We can get started with modules by defining a module in one file and making the module available for use in another file with Node.js module.exports syntax. Every JavaScript file run in Node has a local module object with an exports property used to define what should be exported from the file.
const Data = {};
Data.name = 'Hari';
Data.designation = 'SE';
Data.langauge = 'JavaScript'
module.export = Data;
|| --require()-- ||
To make use of the exported module and the behavior we define within it, we import the module into another file. In Node.js, use the require() function to import modules.
const Data = require('./Data.js');
function displayData(){
console.log(Data.name);
console.log(Data.designation);
console.log(Data.language);
}
displayData();
|| --export default-- ||
Node.js supports require()/module.exports, but as of ES6, JavaScript supports a new more readable and flexible syntax for exporting modules.
let Menu = {};
export default Menu;
let Data = {};
Data.name = 'Hari',
Data.language = [
{
name : 'JavaScript',
type : 'frontEnd'
},
{
name : 'C#',
type : 'backEnd'
}
]
export default Data;
|| --import-- ||
ES6 module syntax also introduces the import keyword for importing objects. In our order.js example, we import an object like this:
import Data from './Data';
function displayData(){
Data.language.forEach(function(element){
console.log(`${element.name} - ${element.type}`);
});
}
displayData();
|| --Named Exports-- ||
let _data = [
{
name : 'hari',
designation : 'SE',
langauge : ['Angular','c#','Java','Python']
},
{
name : 'aryan',
designation : 'SE',
langauge : ['php','testing']
}
]
let requirement = {
_devRequirement : 4,
_testingRequirement : 2
}
let validateRequirement = (_ava,_req)=►{
if(_ava.length ►= _req)
return true;
else
return false;
}
export {_data,requirement,validateRequirement};
|| --Named Imports-- ||
To import objects stored in a variable, we use the import keyword and include the variables in a set of {}.
import {_data,requirement,validateRequirement} from './data;
console.log(requirement)
|| --Export Named Exports-- ||
export let _data = [
{
name : 'hari',
designation : 'SE',
langauge : ['Angular','c#','Java','Python']
},
{
name : 'aryan',
designation : 'SE',
langauge : ['php','testing']
}
]
export let requirement = {
_devRequirement : 4,
_testingRequirement : 2
}
export let validateRequirement = (_ava,_req)=►{
if(_ava.length ►= _req)
return true;
else
return false;
}
|| --Import Named Imports-- ||
To import variables that are declared, we simply use the original syntax that describes the variable name. In other words, exporting upon declaration does not have an impact on how we import the variables.
import {_data,requirement,validateRequirement} from './data'
console.log(requirement);
|| --Export as-- ||
Named exports also conveniently offer a way to change the name of variables when we export or import them. We can do this with the as keyword.
Let’s see how this works. In our menu.js example
let speciallangauge = '';
let isfrontend= function() {
};
let isbackend= function() {
};
export { specialty as chefsSpecial, isVegetarian as isVeg, isLowSodium };
|| --Combining Import Statements-- ||
We can import the collection of objects and functions with the same data.
We can use an import keyword to import both types of variables as such:
import { specialty, isVegetarian, isLowSodium } from './menu';
import GlutenFree from './menu';
No doubt, giving food to a hungry person is indeed a great donation, but the greatest donation of all is to give education. Food gives a momentary satisfaction where as education empowers the person for the rest of his life and enables him to earn his own food.
Let's gift education together
https://www.youtube.com/channel/UC5yQtrJotD8_a0VgYSQqYjg/featured
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «JavaScript Tutorial - 13 - Module Export/Import», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.