module Archives - wiki

Node js export and import

In the first part I am explaining how to do export and import using js.

here is my sample module ‘myutile.js

const myMethod1 = () => {
    console.log('Hi 1')
}
 
const myMethod2 = () => {
    console.log('Hi 2')
}

const myData = {
    name:'myname',
    age:22
}

module.exports = {
    myMethod1, 
    myMethod2,
    myData
};

we can import all from the above module

var access1 = require('./myutile');

access1.myMethod1();

access1.myMethod2();

console.log(access1.myData);

output:

And also we can import only the specific function/data . for example I need to import only the `myMethod2()` and `myData` from the module

var m2 = require('./myutile').myMethod2;
var data = require('./myutile').myData;

m2();

console.log(data);

output:

 


Using Typescript

sample module ‘myutile.js’

export const myMethod1 = () => {
    console.log('Hi 1')
}

export const myMethod2 = () => {
    console.log('Hi 2')
}

export const myData = {
    name: 'myname',
    age: 22
}

export default {
    myMethod1,
    myMethod2,
    myData
};

Importing all

import allUtiles from './myutile';

allUtiles.myMethod1();

allUtiles.myMethod2();

console.log(allUtiles.myData);

output

Importing all

import * as allUtiles  from './myutile';

allUtiles.myMethod2();

allUtiles.myMethod1();

console.log(allUtiles.myData);

output

Importing required

import {myMethod1,myData} from './myutile';

myMethod1();

console.log(myData);

 

 

 

By bm on November 14, 2018 | NodeJs | A comment?
Tags: , , ,