heltonbiker
heltonbiker

Reputation: 27575

how to export and import default function

I have one file which defines a single "default" function, and I want to import it in other:

HelloLog.js:

exports.default = (str) => {
    console.log(`Hello, logging ${str}!`);
}

Client.js:

const HelloLog = require('./HelloLog');

HelloLog.default("foobar"); // do not want

// I'd rather just do this:
HelloLog("foobar")

The fact is I get an error if I do it like in the second call above.

Question is: how should I change HelloLog.js so that second option on file Client.js would work?

Upvotes: 0

Views: 6420

Answers (4)

Tawfik Nasser
Tawfik Nasser

Reputation: 1124

using CommonJS Nodejs Docs

exporting one module :
HelloLog.js :

module.exports = (str) => {
    console.log(`Hello, logging ${str}!`);
}

Client.js :

const HelloLog = require('./HelloLog');

HelloLog("foobar")

using ECMAScript MDN Docs Nodejs Docs

HelloLog.js :

// Default exports choose any
export default expression;
export default function (…) { … } // also class, function*
export default function name1(…) { … } // also class, function*
export { name1 as default, … };

Client.js :

import HelloLog from './HelloLog';

HelloLog("foobar")

  • CommonJS and ECMAScript can't be mixed.

Upvotes: 2

Artur Schens
Artur Schens

Reputation: 136

You are naming your export default. Try this:

export default (str) => {...}

Upvotes: 0

Alexander Smirnov
Alexander Smirnov

Reputation: 408

Or this.

module.exports = (str) => {
  console.log(`Hello, logging ${str}!`);
}
const HelloLog = require('./HelloLog');

HelloLog("foobar");

Upvotes: 1

Sélim Achour
Sélim Achour

Reputation: 728

This should work

HelloLog.js:

exports.HelloLog = (str) => {
    console.log(`Hello, logging ${str}!`);
}

Client.js:

const { HelloLog } = require('./HelloLog');

Upvotes: 0

Related Questions