listenlight
listenlight

Reputation: 662

How to export & import custom helpers in JS/React?

Task :


Tried Case :

Problem :

Open to all suggestions.
Please suggest.
Thank you.

log = (arg, ...argv) => console.log(arg, ...argv)
err = (arg, ...argv) => console.error(arg, ...argv)
error = (arg, ...argv) => console.error(arg, ...argv)
info = (arg, ...argv) => console.info(arg, ...argv)
warn = (arg, ...argv) => console.warn(arg, ...argv)

// how to export? should this be a class?

Upvotes: 4

Views: 1928

Answers (2)

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20118

General keyword to export function in ES6 is export (custom export function file)

export const functionName = (arg, ...argv) => {
   console.log(arg, ...argv)
}

General keyword to import function in ES6 is import (custom import function file)

import { functionName } from './export_function_file';

Upvotes: 1

Amruth
Amruth

Reputation: 5912

yes you can shorthand.

Create a file ex : log.js with below functions.

export const log = (arg, ...argv) => {
    console.log(arg, ...argv)
}
export const err  = (arg, ...argv) => {
  console.error(arg, ...argv)
} 
export const error   = (arg, ...argv) => {
   console.error(arg, ...argv)
}

export const info   = (arg, ...argv) => {
  console.info(arg, ...argv)
}

export const warn   = (arg, ...argv) => {
   console.warn(arg, ...argv)
}


Later you just import these functions in other component where you want to use.

import {log, err, error, info, warn} from './log'; //path may be different

Then just call functions wherever you want.

log('hi', [1,2,3]);
err('hi', [1,2,3]);
error('hi', [1,2,3]);
info('hi', [1,2,3]);
warn('hi', [1,2,3]);

Upvotes: 3

Related Questions