Skip to content Skip to sidebar Skip to footer

What Is The Syntax To Export A Function From A Module In Node.js?

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;

Solution 1:

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:

Solution 2:

to expose both foo and bar functions:

module.exports = {
   foo: function() {},
   bar: function() {}
}

Solution 3:

You can also do this in a shorter form

// people.jsfunctionFoo() {
  // ...
}

functionBar() {
  // ...
}

module.exports = { Foo, Bar}

Importing:

// index.jsconst { Foo, Bar } = require('./people.js');

Solution 4:

exportfunctionfoo(){...};

Or, if the function has been declared earlier:

export {foo};

Reference: MDN export

Post a Comment for "What Is The Syntax To Export A Function From A Module In Node.js?"