Select functions to import from module - javascript

If we have a module like:
const ourModule = (() => {
const add = (a,b) a+b
const sub = (a,b) return a-b
return { add, sub }
})();
export default ourModule;
So we import like:
import ourModule from 'path'
And call the functions like:
ourModule.add(1,2)
But how we can import it to use it directly?
like just add(1,2) instead of ourModule.add(1,2)

Use named exports instead:
export const add = (a,b) => a+b;
export const sub = (a,b) => a-b;
Then they can be imported like:
import { add } from './your/module';

You're looking for destructuring imports:
function add() {
}
function sub() {
}
module.exports = { add, sub };
Then you can do:
import { add, sub } from "./MyModule"

Related

How to export multiple functions Javacript?

I want to export default all functions inside export default, but every time I try to import them in another file, I get the error that the functions don't exists. Am I importing wrong?
export default () => {
// methods
const makeRequest = async () => {
async function useAllBenefits() {
...
return payload;
}
async function useTopBenefits() {
...
return payload;
}
// exposed
return {
useAllBenefits,
useTopBenefits,
makeRequest
};
};
}
myotherfile.js
import all from '../myFile'
console.log(all.useAllBenefits)
Don't put them inside another function
Use the export keyword
Such:
export const aFunction = () => {};
export const anOtherFunction = () => {};
const someDefaultExport = () => {};
export default someDefaultExport;
Then you can import them:
import theDefault, { aFunction, anOtherFunction } from "../myFile";
If you want to export multiple functions AS DEFAULT you can do it by exporting one object whose properties are functions.
export default {
function1: () => {},
function2: () => {},
function3: () => {}
}
Now in another file you can import them and use as bellow:
import all from '../myFile.js';
all.function1();
all.function2();
Method 1. export each functions
myFunction.js
export const sum = (a,b) {
return a + b;
}
export const multiply = (a,b) {
return a * b;
}
Method 2.
myFunction.js
const sum = (a,b) {
return a + b;
}
const multiply = (a,b) {
return a * b;
}
export default {sum, multiply}
Import section
file.js
import all from './myFunction.js'
all.sum(10, 11);
Or
file.js
import {sum, multiply} from './myFunction.js'
sum(10, 11);

rename named export without export default

I do have an issue when I want to decorate my export with a wrapper.
I have a wrapper/hof function that encapsulate the real function like this:
import { withSth } from './anotherFile'
import { someConst } from './someConst'
const myFunc = () => {}
export {
myFunc: withSth(someConst, myFunc)
}
Parsing error: ',' expected.
This does not work while this work:
import { withSth } from './anotherFile'
import { someConst } from './someConst'
const myFunc = () => {}
module.exports = {
myFunc: withSth(someConst, myFunc)
}
The only way i can do this is like this:
import { withSth } from './anotherFile'
import { someConst } from './someConst'
const myFuncX = () => {}
const myFunc = withSth(someConst, myFuncX)
// OR
// const myFync = withSth(someConst, () => {})
// but it lose readability
module.exports = {
myFunc
}
My point is how can I do the same thing with export and without using default export and renaming all my function
module.exports = {
methodA: withSth(param, methodA),
methodB: withSth(param, methodB),
methodC: withSth(param, methodC),
methodD: withSth(param, methodD),
}
Unlike Commonjs modules (with module.exports), ES6 modules do not export values but variable bindings. You must declare a variable1, you cannot export something unnamed. So your choices are only
export const myFunc = withSth(someConst, myFuncX);
const myFuncX = () => {};
export const myFync = withSth(someConst, () => {});
const myFuncX = () => {};
const myFyncY = withSth(someConst, () => {});
export { myFuncY as myFunc }
1: with the exception of export default …;, which implicitly declares a variable with an unforgeable name for you. But you want multiple named exports.

How to convert class with static items to module file

I have a class like this:
export default class {
static myConnection = GHD.initConnection();
static getCards = () => this.myConnection.getCards();
}
And I call it as:
import connector from '../path.js';
connector.getCards();
I would like to convert this class with static items to module basically I don't want to use class.
Is this possible?
I tried something like:
module.exports {
myConnection: GHD.initConnection();
getCards: () => this.myConnection.getCards();
}
but this doesn't work.
Update with real code values requested in comments:
export default class {
static firebaseReference = RNFirebase.initializeApp();
static getDatabase = () => this.firebaseReference.database();
static getUser = () => this.firebaseReference.auth().currentUser;
}
You're probably looking for
export const myConnection = GHD.initConnection();
export const getCards = () => myConnection.getCards();
then
import * as connector from '../path.js';
connector.getCards();
or
import { getCards } from '../path.js';
getCards();
If you must keep compatibility with the default import syntax, you can use
export const myConnection = GHD.initConnection();
export const getCards = () => myConnection.getCards();
/** #deprecated */
export default { myConnection, getCards };

Exporting an Object directly?

I'm trying to export an object directly, but I'm not getting the results I'd like;
const cmd = {
name: "testFunc",
desc: "Test",
execute(name, args) {
console.log("Test ()");
}
}
export {cmd}
I import it as follows;
import(`./commands/${file}`).then(cmd => {
console.log(cmd.cmd.name);
})
But I would rather be able to just do cmd.name, rather than cmd.cmd.name.
Don't export an object, use individual named exports instead:
export const name = testFunc";
export const desc = "Test";
export function execute(name, args) {
console.log("Test ()");
}
Alternatively, change your import statement to use destructuring:
import(`./commands/${file}`).then(({cmd}) => {
console.log(cmd.name);
})

ES6 default and named exports

I am trying to understand named and default exports. I have a seemingly basic requirement which I don't understand how to setup.
I want to be able to import both:
//app.js
import Mod from './my-module'
import { funcA, funcB } from './my-module'
console.log('A', Mod.funcA(), funcA()); // A a a
console.log('B', Mod.funcB(), funcB()); // A a a
When I try, the closest way of doing this I get to is the following:
//my-module.js
export function funcA() { return 'a'; };
export function funcB() { return 'b'; };
export default {funcA, funcB}
My trouble is that I don't want to reindex each functions in the default export. I just want to define my functions and then make sure they are exported so I can use them either way.
Suggestions? Or do I have to use import * as Mod from './my-module';?
You can omit the default export and use import as syntax:
//app.js
import * as Mod from './my-module'
import { funcA, funcB } from './my-module'
console.log('A', Mod.funcA(), funcA()); // A a a
console.log('B', Mod.funcB(), funcB()); // B b b
//my-module.js
export function funcA() { return 'a'; };
export function funcB() { return 'b'; };
Import entire module's contents once using * as name:
import * as Mod from './my-module';
Then assign them to separate constants using destructuring:
const { funcA, funcB } = Mod;
For export just use the named exports:
export function funcA() { return 'a'; };
export function funcB() { return 'b'; };

Categories