How can I export all functions from a file in JS?
Asked Answered
O

12

112

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.

Other answered 2/4, 2018 at 18:25 Comment(3)
Possible duplicate of ES6 export all values from objectCellulose
@Hamms: Except the OP doesn't have an object, so...Ligniform
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'Toothsome
L
132

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 => {
    // ...
};
Ligniform answered 2/4, 2018 at 18:28 Comment(1)
You can search and replace ^function with export functionEncounter
T
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();
Toothsome answered 2/4, 2018 at 18:36 Comment(3)
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://mcmap.net/q/195902/-globally-imported-variables-are-undefined has found a remedy.Outing
This worked in my case but I wasn't able to run the file without adding "type": "module", in my packege.json.Postconsonantal
@Postconsonantal Note that you need "type": "module" in package.json when you're using pure NodeJS.Toothsome
C
31

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";
Candidate answered 15/2, 2020 at 22:55 Comment(4)
You don't need to write out the names twice. just module.exports ={myFunction,otherFunction} will work just the same.Inerrable
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!Candidate
what if i want to export all the functions in a file with module.exports = { func1, func2, func3 } and I want to import them all? what should I write? import * from '../myfile.js' does not work...Kinslow
@Don Diego, I am not sure about import. This question was about exporting functions.Candidate
M
26

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'
Microphyte answered 10/12, 2020 at 5:20 Comment(2)
Are you sure this export a = () => {} works? I get Declaration or statement expected.Windowlight
@Windowlight Looks like I forgot to add const keyword. Let me update my answer. But, this should work. export const a = () => {}Microphyte
B
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'
Barcroft answered 9/10, 2019 at 14:34 Comment(0)
I
9

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();
Introvert answered 21/10, 2020 at 17:38 Comment(0)
D
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()

Deepen answered 6/9, 2019 at 15:0 Comment(3)
Actually, how can we use that workaround with import and not require?Ctenoid
Node below v12 doesn't support es6 import/export. However you will be able to use this in other places. See #34278974Deepen
Or, something along the lines of exports.signUp = () => "user" can also workToothsome
G
3

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

const hello = () => "hello there"
const bye = () => "bye bye"
export default { hello, bye }
Glassman answered 17/1, 2023 at 17:36 Comment(0)
C
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
Clavate answered 24/5, 2021 at 21:9 Comment(0)
P
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
Protease answered 18/2, 2023 at 16:37 Comment(0)
P
0

There is not much to do but to export them manually, if you want to automate this process you could start by doing it with babel, here I show you an example on how could this be done.

var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");

// Initialize Ace Editor for read-only
var editor2 = ace.edit("editor2");
editor2.setTheme("ace/theme/monokai");
editor2.getSession().setMode("ace/mode/javascript");
editor2.setReadOnly(true);

// Function to trigger transformation
function transformCode() {
  try {
    // Get the code from the first editor
    var code = editor.getValue();
    // Transform the code
    const transformedCode = astTransform(code);
    // Update the content of the second editor with the transformed code
    editor2.setValue(transformedCode);
  } catch (error) {
    console.error("Error during transformation:", error);
  }
}

function astTransform(code) {
  const result = Babel.transform(code, {
    plugins: [{
      visitor: {
        Program(path) {
          //console.log(path.scope);
          const {
            types: t
          } = Babel.packages;
          path.pushContainer('body', [t.exportNamedDeclaration(null, Object.keys(path.scope.bindings).map(_ => t.exportSpecifier(t.identifier(_), t.identifier(_))))]);
          /*t.addComment(path.container, "trailing", `This is what I found:
Identifiers defined in this scope: ${JSON.stringify(Object.keys(path.scope.bindings))};
Identifiers used that are global or in prelude scope: ${JSON.stringify(Object.keys(path.scope.globals))}
All variables used at all: ${JSON.stringify(Object.keys(path.scope.references))}
`);*/
        }
      }
    }]
  });
  return result.code;
}
.editor {
  width: 500px;
  height: 60px;
  border: 1px solid lightgray;
}
<!-- Include Ace Editor from CDN -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src-min-noconflict/ace.js"></script>

<!-- Create a div element for Ace Editor -->
<div id="editor" class="editor">function greet() {
  console.log('Hello, world!');
}
var a = 1;
const b = a + a;
((_ => {
  var ignored = 1;
  console.log(ignored)
}))();
</div>
<button onclick="transformCode()">Add Exports</button>
<div class="editor" id="editor2" readonly></div>

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
Piker answered 13/4 at 8:14 Comment(0)
C
0

You can use literal,

a js file

const allFunctions = {
value:1,
func1:()=>{
return this.value;},
func2:()=>{
return allFunctions.func1(); /use inside },
func3:()=>{return this.value; }
}
export default allFunctions

another js file //

import allFunctions from './allFunctions'
const {func1,func2,func3} = allFunctions

also you can use literal functions as a chain methods. Like,

const result = allFunctions.func1().func2().func3();
Coverture answered 13/4 at 9:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.