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?
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")
Or this.
module.exports = (str) => {
console.log(`Hello, logging ${str}!`);
}
const HelloLog = require('./HelloLog');
HelloLog("foobar");
This should work
HelloLog.js:
exports.HelloLog = (str) => {
console.log(`Hello, logging ${str}!`);
}
Client.js:
const { HelloLog } = require('./HelloLog');
You are naming your export default
. Try this:
export default (str) => {...}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.