使用ES5语法在Node中混合使用默认导出和命名导出 [英] Mixed default and named exports in Node with ES5 syntax
问题描述
我在导出/导入模块方面的所有经验都来自使用 export
和 import
的ES6,在这里您可以执行类似的操作以使单个模块导出默认功能以及单独的命名函数.
All my experience with exporting/importing modules has come in ES6 using export
and import
, where you can do something like this to have a single module export a default function as well as separate named functions.
// module.js
export default mainFunction
export { namedFunction }
// main.js
import mainFunction from 'functions'
mainFunction()
import { namedFunction } from 'function'
namedFunction()
但是我不知道如何使用 module.exports
和 require
进行ES5样式导入.据我了解,我可以导出一个默认值:
However I can't figure out how to do this with ES5 style imports using module.exports
and require
. As far as I understand, I can export either a single default:
// module.js
module.exports = function mainFunction() {}
// main.js
const mainFunction = require('module.js')
或者我可以创建命名的出口:
Or I can create named exports:
// module.js
module.exports = {
namedFunction: function() {}
}
// main.js
const namedFunction = require('module.js').namedFunction
但是我不能两者都做.我以为我可以这样命名导出中的一个默认",但这是行不通的
But I can't do both. I thought I could maybe name one of the exports "default" like this, but it doesn't work
// module.js
module.exports = {
default: function() {},
namedFunction: function() {}
}
// main.js
const mainFunction = require('module.js') // does not work
const mainFunction = require('module.js').default // works, but not what I want
const namedFunction = require('module.js').namedFunction
如何使用ES5完成此双重默认/命名导出?
How can I accomplish this dual default/named export with ES5?
推荐答案
您想要将 module.exports
的值分配为默认函数,然后将所有命名的导出作为属性放在该功能.
You want to assign the value of module.exports
to be your default function, and then put all the named exports as properties on that function.
const defaultFunction = () => { console.log('default!'); };
const namedFunction1 = () => { console.log('1!'); };
const namedFunction2 = () => { console.log('2!'); };
const myModule = module.exports = defaultFunction;
myModule.namedFunction1 = namedFunction1;
myModule.namedFunction2 = namedFunction2;
假设这是在 myModule.js
中.然后,您可以执行以下操作:
Let's say that was in myModule.js
. Then you can do this:
const myModule = require('./myModule');
myModule(); // Prints: 'default!'
myModule.namedFunction1(); // Prints: '1!'
这篇关于使用ES5语法在Node中混合使用默认导出和命名导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!