Javascript: Modules
We will use MVC pattern with following structure.
src
--js
--models
Search.js
--views
searchView.js
index.js
Default export
We want to export just one thing, we dont specify any variable.
//Search.js
export default 'I am an exported string.'
//index.js
//str is name which we will use in index.js
import str from './models/Search';
Named export
We want to export multiple things, we need to specify any variables.
//Search.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
export const ID = 23;
//index.js
import {add, multiply} from './models/Search';
console.log(`Using imported functions. ${add(ID,2)} and ${multiply(3, 5)}`);
We can use different names for our functions.
//index.js
import {add as a, multiply as m} from './models/Search';
console.log(`Using imported functions. ${a(ID,2)} and ${m(3, 5)}`);
We can import also everything.
//index.js
import * as searchModel from './models/Search';
console.log(`Using imported functions. ${searchModel.add(searchModel.ID,2)} and ${searchModel.m(3, 5)}`);