Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import, rename, and export a function in JavaScript?

Tags:

javascript

With JavaScript what's the shortest way to import a named export, rename it, and export it again?

This code works but it feels more verbose than it should be

import { mock as myFunctionMock } from 'context/myFunction';
export const myFunction = myFunctionMock;
like image 507
Evanss Avatar asked Mar 25 '19 14:03

Evanss


People also ask

Can you export a function in JavaScript?

To export multiple functions in JavaScript, use the export statement and export the functions as an object. Alternatively, you can use the export statement in front of the function definitions. This exports the function in question automatically and you do not need to use the export statement separately.

Can you import a function in JavaScript?

Use JavaScript import() to dynamically load a module. The import() returns a Promise that will be fulfilled once the module is loaded completely. Use the async / await to handle the result of the import() .


2 Answers

You can combine the import and export like so:

export { mock as myFunctionMock } from 'context/myFunction';

See MDN Docs

Note that you won't actually be able to use myFunctionMock within your code file since you haven't imported it. Neither mock nor myFunctionMock will be defined within this module.

This is a useful shorthand when you're building a library that will be used by other modules or by your end-user.

For example, if you had a utils library that you wanted to export, but you wanted to organize your util functions across several smaller files, such as stringUtils, objectUtils, dataUtils, etc, you can export the contents of those modules within your utils module to create a single, monolithic access point:

stringUtils.js

export function toLower(){}

export function toUpper(){}

objectUtils.js

export function propertyMap(){}

utils.js

export {
    toLower as stringToLower,
    toUpper as stringToUpper,
} from "stringUtils.js";
export {
    propertyMap as objectPropertyMap
} from "objectUtils.js";

I wouldn't generally recommend this approach for internal code as it can make your dependency trees a bit wonky in some cases. It can, however, be extremely useful in situations where you want to import from a common interface but the implementation is dependent on the build (prod vs dev, web vs node, etc)

like image 110
JDB Avatar answered Oct 16 '22 09:10

JDB


import { mock as myFunction } from 'context/myFunction';
export { myFunction };
like image 45
Smolin Pavel Avatar answered Oct 16 '22 10:10

Smolin Pavel