javascript – how to export and import default function

javascript – how to export and import default function

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 cant be mixed.

Or this.

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

HelloLog(foobar);

javascript – how to export and import default function

This should work

HelloLog.js:

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

Client.js:

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

Leave a Reply

Your email address will not be published.