105

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.

JakAttk123
  • 1,646
  • 3
  • 11
  • 19
  • Possible duplicate of [ES6 export all values from object](https://stackoverflow.com/questions/29844074/es6-export-all-values-from-object) – Hamms Apr 02 '18 at 18:27
  • 3
    @Hamms: Except the OP doesn't have an object, so... – T.J. Crowder Apr 02 '18 at 18:29
  • 2
    I'd consider exporting an Object containing all the functions: `export default { fn1(), fn2(), ... }`, or wrapping them inside a `class` then `export default MyClass`. One other solution is to put `export` in front of every functions and `import * as MyConverter from './myconverter.js'` – ionizer Apr 02 '18 at 18:29

10 Answers10

124

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 => {
    // ...
};
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 7
    @Bergi: I agree (other than possible arguments for arrow functions being lightweight), just wanted to ensure the OP knew where and how to apply `export` to what they're doing. – T.J. Crowder Apr 02 '18 at 22:20
  • You can search and replace `^function` with `export function` – Ooker Jul 17 '23 at 07:42
65

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();
ionizer
  • 1,661
  • 9
  • 22
  • First I thought very nice, then I can also export and import my "global" variables. Unfortunately the imported things are read-only. I don't know why, but https://stackoverflow.com/a/58402982/1707015 has found a remedy. – qräbnö Jul 01 '20 at 00:23
  • This worked in my case but I wasn't able to run the file without adding "type": "module", in my packege.json. – moghwan Sep 01 '20 at 11:49
  • 1
    @moghwan Note that you need `"type": "module"` in package.json when you're using pure NodeJS. – ionizer Sep 02 '20 at 20:51
28

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";
scot
  • 1,194
  • 14
  • 26
  • 5
    You don't need to write out the names twice. just module.exports ={myFunction,otherFunction} will work just the same. – sirclesam Oct 24 '21 at 02:43
  • 1
    yes, this is true, i was just showing you could write it to also export "myrandofunc" as "thisisabettername_forthefunction" although then i don't why you wouldn't just rename the function anyway! lmao @ me - sometimes i like being pedantic? but yes thanks! – scot Nov 11 '21 at 09:00
23

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'
coderpc
  • 4,119
  • 6
  • 51
  • 93
  • 1
    Are you sure this `export a = () => {}` works? I get `Declaration or statement expected.` – Qwerty Jan 07 '21 at 02:06
  • 2
    @Qwerty Looks like I forgot to add `const` keyword. Let me update my answer. But, this should work. `export const a = () => {}` – coderpc Jan 07 '21 at 18:29
11

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'
CloudBranch
  • 1,434
  • 3
  • 18
  • 23
8

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();
Emzaw
  • 618
  • 6
  • 11
6

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()

Pavindu
  • 2,684
  • 6
  • 44
  • 77
  • Actually, how can we use that workaround with import and not require? – Joseph Paz Aliaga Oct 25 '19 at 19:51
  • 1
    Node below v12 doesn't support es6 import/export. However you will be able to use this in other places. See https://stackoverflow.com/questions/34278474/module-exports-and-es6-import – Pavindu Oct 26 '19 at 00:46
  • Or, something along the lines of `exports.signUp = () => "user"` can also work – ionizer Nov 20 '19 at 09:25
2

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
alditis
  • 4,633
  • 3
  • 49
  • 76
2

In case anyone still needs an answer to this in modern JavaScript:

const hello = () => "hello there"
const bye = () => "bye bye"
export default { hello, bye }
0

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
tommyn
  • 1