0

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?

heltonbiker
  • 26,657
  • 28
  • 137
  • 252
  • you have to use `module.exports = (str) => {` to use `HelloLog("foobar")` – aRvi Sep 25 '20 at 19:50
  • Does this answer your question? [How to get Javascript's IMPORT EXPORT working. Do I need transpiler?](https://stackoverflow.com/questions/56959001/how-to-get-javascripts-import-export-working-do-i-need-transpiler) – mwilson Sep 25 '20 at 19:53

4 Answers4

2

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.
Tawfik Nasser
  • 1,018
  • 9
  • 17
  • So basically we have `exports.default`, `module.exports`, and maybe `module.exports.default`? No, wait, the third form is not valid... This is giving me a headache already... – heltonbiker Sep 25 '20 at 19:59
  • 1
    when you did `module.exports.default` you actually added default prop to the exported object `{default : (str)=>{}}` [check out the documentations](https://nodejs.org/api/modules.html#modules_exports_shortcut) – Tawfik Nasser Sep 25 '20 at 20:04
  • `module.exports.anyThing` and `module.exports.default` there is no saved word as i know. no default or any other word. then in your code you will do `const { anyThing , default, } = require('./Hello')` while if you don't want to use the exports object you shall do as i wrote in my answer. – Tawfik Nasser Sep 25 '20 at 20:10
1

Or this.

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

HelloLog("foobar");

0

This should work

HelloLog.js:

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

Client.js:

const { HelloLog } = require('./HelloLog');
Sélim Achour
  • 718
  • 4
  • 7
0

You are naming your export default. Try this:

export default (str) => {...}
Artur Schens
  • 116
  • 4