How can I export all functions from a file in JS? - javascript

I'm creating a unit converter, and I want to put all of the conversion functions into their own file. Using ES6 export, is there any way to export all of the functions in the file with their default names using only one line? For example:
export default all;
The functions are all just in the file, not within an object.

No, there's no wildcard export (except when you're re-exporting everything from another module, but that's not what you're asking about).
Simply put export in front of each function declaration you want exported, e.g.
export function foo() {
// ...
}
export function bar() {
// ...
}
...or of course, if you're using function expressions:
export var foo = function() {
// ...
};
export let bar = () => {
// ...
};
export const baz = value => {
// ...
};

I think there are a lot of solutions to this. And as has been answered, there's no wildcard export. But, you can 'wildcard' the import. So, I much prefer the one putting export before each of the functions you want to expose from the file:
//myfile.js
export function fn1() {...}
export function fn2() {...}
and then import it like so:
import * as MyFn from './myfile.js'
Afterwards you could use it like so:
MyFn.fn1();
MyFn.fn2();

You can also use module.exports as follows:
function myFunction(arg) {
console.debug(arg);
}
function otherFunction(arg) {
console.error(arg);
}
module.exports = {
myFunction: myFunction,
otherFunction: otherFunction,
};
Then you can import it:
import {myFunction, otherFunction} from "./Functions.js";

In my use case, I do have three reusable functions in one file.
utils/reusables.js
export const a = () => {}
export const b = () => {}
export const c = () => {}
In order to point the root folder instead of individual file names, I created a file called index.js which will comprise of all the functions that are listed in individual files.
utils/index.js
export * from './reusables'
Now, when I want to use my a function, I will have to simply import it like this
import { a } from '../utils'
Rather than calling it from its individual files
import { a } from '../utils/reusables'

You could also export them at the bottom of your script.
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = {
options: {
color:'white',
thickness:'2px'
},
draw: function() {
console.log('From graph draw function');
}
}
export { cube, foo, graph };
You can also aggregate submodules together in a parent module so that they are available to import from that module.
// In parentModule.js
export { myFunction, myVariable } from 'childModule1.js';
export { myClass } from 'childModule2.js';
// In top-level module
import { myFunction, myVariable, myClass } from 'parentModule.js'

For Node.js environment, what I did to export functions was this.
UserController.js
module.exports = {
signUp: () => {
return "user"
},
login: () => {
return "login"
}
}
UserRouter.js
const UserController = require('./UserController')
then login and signUp functions could be used inside UserRouter as UserController.signUp() and UserController.login()

I think there's a missing common solution, which is exporting in index.js file:
myModule/myFunctions.js
export const foo = () => { ... }
export const bar = () => { ... }
then in myModule/index.js
export * from "./myFunctions.js";
This way you can simply import and use it with:
import { foo, bar } from "myModule";
foo();
bar();

functions.js
function alpha(msj) {
console.log('In alpha: ' + msj);
}
function beta(msj) {
console.log('In beta: ' + msj);
}
module.exports = {
alpha,
beta
};
main.js
const functions = require('./functions');
functions.alpha('Hi');
functions.beta('Hello');
Run
node main.js
Output
In alpha: Hi
In beta: Hello

In case anyone still needs an answer to this in modern JavaScript:
const hello = () => "hello there"
const bye = () => "bye bye"
export default { hello, bye }

What I like to do is to export all functions within an object:
//File.js
export default {
testFunction1: function testFunction1(){
console.log("Hello World")
},
//a little bit cleaner
testFunction2: () => {
console.log("Nothing here")
}
}
Now you can access the functions with calling the key value of the object:
//differentFile.js
import file from 'File.js'
file.testFunction1()
//Hello World
file.testFunction2()
//Nothing here

Related

Get function inside default export function

I have function inside user.js with default export like this
export default {
var getListFriends = async (accessToken) =>{
}
....other function
return {
getListFriends,
...other function...
}
}
then I import it to index.js
import userService from './user';
Then I will add only index.js to plugin.
I can call this.$userService (it shows as anonymous function) but this.$userService.getListFriends return undefined.
How can I call function getListFriends from import.
Thank you very much.
where is user.js?
if its inside plugins directory, you have to use inject to add it to your nuxt.
then you can access it via nuxt object inside your code.
see this example from nuxt docs:
export default ({ app }, inject) => {
// Inject $hello(msg) in Vue, context and store.
inject('hello', msg => console.log(`Hello ${msg}!`))
}
you can see the full document here
ok now for this to work the way you want you need to change your user.js file,
export default {
friends: () => {
console.log('hi bro');
},
notFriends: () => {
console.log('go away man im not your bro');
}
};
something like this.
you dont need inject or app in your user.js.
and your code problem is that you are defining a function and trying to access it's inner values from the outside like:
function boo() {
var b = 0;
}
you can not access the value of b with boo.b. its a local variable to the boo function
instead create a object and have multiple functions inside your object

React Constants inside a Function

I need help to export the constants. I am getting different errors when i try to search for this on google or other related topics at stackoverflow.
This is my Printer.jsx
import React, { useRef, useState } from "react";
// export individual features (can export var, let,
// const, function, class)
export let ePosDev = new window.epson.ePOSDevice();
export const ePosDevice = useRef();
export const printer = useRef();
export function connectFunction() {
ePosDevice.current = ePosDev;
ePosDev.connect("192.168.1.254", 8080, (data) => {
if (data === "OK") {
ePosDev.createDevice(
"local_printer",
ePosDev.DEVICE_TYPE_PRINTER,
{ crypto: true, buffer: false },
(devobj, retcode) => {
if (retcode === "OK") {
printer.current = devobj;
} else {
throw retcode;
}
}
);
} else {
throw data;
}
}); };
I need to add the const connect to the App.js so that if the App is starting the connection is also starting. The second is that i need to add the const print to ReactB.js-file so if content of ReactB.js-page is loading the print-request should be send.
Thanks for your help! Stuck at this since 5 hours and dont know how to deal with this problems.
It seems your main issue stems around how to export constants. I recommend checking out MDN for more info: https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
Below is an excerpt on named exports that is relevant to your scenario.
// export features declared earlier
export { myFunction, myVariable };
// export individual features (can export var, let,
// const, function, class)
export let myVariable = Math.sqrt(2);
export function myFunction() { ... };
So for your example, it would just be a matter of adding declaring the const with export const connect = value; or adding export { connect }; after it is declared.

How can i use module.exports.function in es6? [duplicate]

This question already has answers here:
module.exports vs. export default in Node.js and ES6
(3 answers)
Closed 4 years ago.
I am trying to convert this code to es6 so for my react project, but I couldn't figure out(didn't get an error but couldn't achieve what I wanted to do).
here are the files.
foo.js
module.exports = () => {
console.log("hello default");
}
module.exports.bar = () => {
console.log("one functions");
}
index.js
const foo = require("./foo");
foo();
foo.bar();
I want be able to do this without using NAMED exports.
With ES6, you can make use of export and import instead of require and module.exports
export default () => {
console.log("hello default");
}
export const bar = () => {
console.log("one functions");
}
index.js
import foo, { bar} './foo';
foo();
bar();
EDIT: In order to replicate the same exact behaviour, you can leverage the fact the Javascript functions are essentially objects and you can assign more properties to them
const foo = () => {
console.log("hello default");
};
foo.bar = () => {
console.log("one functions");
};
export default foo;
Working demo
function needsAName () => {
console.log("hello default");
}
function bar () {
console.log("one functions");
}
export default {needsAName, bar}
To use it:
import functions from './Container'
functions.needsAName()
functions.bar()

How to import anonymous functions in ES6

In ES6, we can import exported modules like this:
import { Abc } from './file-1'; // here Abc is a named export
import Def from './file-2'; // here Def is the default export
But how can we import anonymous functions? Consider this code:
file-3.js:
export function() {
return 'Hello';
}
export function() {
return 'How are you doing?';
}
How can I import above two functions in another file, given that neither are they default exports nor are they named exports (anonymous functions don't have names!)?
Single anonymous function can be exported as default (default export value can be anything). Multiple anonymous functions cannot be exported from a module - so they cannot be imported, too.
export statement follows strict syntax that supports either named or default exports. This will result in syntax error:
export function() {
return 'Hello';
}
These functions should be named exports:
export const foo = function () {
return 'Hello';
}
export const bar = function () {
return 'How are you doing?';
}
So they can be imported under same names.

Correct way to export object in es6 module

I'm trying to export an my module as an object but exporting it seems an 'anti pattern' (https://medium.com/#rauschma/note-that-default-exporting-objects-is-usually-an-anti-pattern-if-you-want-to-export-the-cf674423ac38)
So I was wondering what's the correct way to export an object and then use it as
import utils from "./utils"
`
utils.foo()
Currently I'm doing like so
/** a.js **/
function foo(){
//...
}
export {
foo
}
/** b.js **/
import * as utils from "a";
utils.foo()
is it correct like so? Do I maintain the tree-shaking feature?
thanks
If the object you want to import/export only contains some functions (as I assume due to the Utils name), you can export the functions separately as follows:
export function doStuff1() {}
export function doStuff2() {}
And import like this:
import {doStuff1, doStuff2} from "./myModule";
However, if the object you want to export holds state in addition to methods, you should stick to a simple export default myObject. Otherwise, calling the imported methods won't work as intended, since the context of the object is lost.
As an example, the following object should be exported as a whole, since the properties of the object should stay encapsulated. Only importing and calling the increment function would not mutate myObject since the context of the object cannot be provided (since it's not imported as a whole).
const myObject = {
counter: 0,
increment: function() {
this.counter++;
}
}
export default myObject;
es6 native way to do this:
// file1.es6
export const myFunc = (param) => {
doStuff(param)
}
export const otherFunc = ({ param = {} }) => {
doSomething({ ...param })
}
// file2.es6
import { otherFunc } from './file1.es6'
import * as MyLib from './file1.es6'
MyLib.myfunc(0)
MyLib.otherFunc({ who: 'Repley' })
otherFunc({ var1: { a1: 1 } })
And so on.

Categories

Resources