8

What is the syntax to export a function from a module in Node.js?

function foo() {}
function bar() {}

export foo; // I don't think this is valid?
export default bar;
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 1
    Possible duplicate of [What is "export default" in javascript?](https://stackoverflow.com/questions/21117160/what-is-export-default-in-javascript) – Erazihel Jul 18 '17 at 16:05
  • 5
    Absolutely not a duplicate. This is a matter of feature support in the current Node build. What's with the downvotes, people? – salezica Jul 18 '17 at 16:07

4 Answers4

18

In Node you export things with module.exports special object. For example:

This exports both functions:

module.exports = { foo, bar };

They can be used as:

const { foo, bar } = require('./module/path');

To export one of those functions as top-level object you can use:

module.exports = foo;
module.exports.bar = bar;

which can be used as:

const foo = require('./module/path');

and:

const { bar } = require('./module/path');

or:

const foo = require('./module/path');
const { bar } = foo;

or:

const foo = require('./module/path');
const bar = foo.bar;

etc.

This is "the syntax to export a function from a module in Node.js" as asked in the question - i.e. the syntax that is natively supported by Node. Node doesn't support import/export syntax (see this to know why). As slezica pointed put in the comments below you can use a transpiler like Babel to convert the import/export keywords to syntax understood by Node.

See those answers for more info:

rsp
  • 107,747
  • 29
  • 201
  • 177
  • Ah, thank you. And what is the ES2015 module syntax for the same? – Ben Aston Jul 18 '17 at 16:04
  • 1
    This is the only way until Node starts supporting `import`/`export` ES6 syntax, **which it currently does not**. You can also use Babel, installing `babel-cli` and `babel-preset-latest` as dev-dependencies, then precompiling your javascript or running `babel-node`. I do this for all my projects – salezica Jul 18 '17 at 16:04
3

to expose both foo and bar functions:

module.exports = {
   foo: function() {},
   bar: function() {}
}
Jarek Kulikowski
  • 1,399
  • 8
  • 9
2

You can also do this in a shorter form

// people.js
function Foo() {
  // ...
}

function Bar() {
  // ...
}

module.exports = { Foo, Bar}

Importing:

// index.js
const { Foo, Bar } = require('./people.js');
Praveen Govind
  • 2,619
  • 2
  • 32
  • 45
2
export function foo(){...};

Or, if the function has been declared earlier:

export {foo};

Reference: MDN export

ingdc
  • 760
  • 10
  • 16