使用ES5语法在Node中混合使用默认导出和命名导出

Rya*_*lio 5 javascript node.js ecmascript-5 node-modules

我在导出/导入模块方面的所有经验都来自使用export和的ES6中import,您可以在其中执行类似的操作,以使单个模块导出默认函数以及单独的命名函数。

// module.js
export default mainFunction
export { namedFunction }

// main.js
import mainFunction from 'functions'
mainFunction()

import { namedFunction } from 'function'
namedFunction()
Run Code Online (Sandbox Code Playgroud)

但是我不知道如何使用module.exports和使用ES5样式导入来做到这一点require。据我了解,我可以导出一个默认值:

// module.js
module.exports = function mainFunction() {}

// main.js
const mainFunction = require('module.js')
Run Code Online (Sandbox Code Playgroud)

或者我可以创建命名的导出:

// module.js
module.exports = {
  namedFunction: function() {}
}

// main.js
const namedFunction = require('module.js').namedFunction
Run Code Online (Sandbox Code Playgroud)

但是我不能两者都做。我以为可以这样命名出口之一“默认”,但它不起作用

// 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
Run Code Online (Sandbox Code Playgroud)

如何使用ES5完成双重默认/命名双重导出?

Tro*_*ott 8

您希望将值module.exports设为默认函数,然后将所有命名的导出作为该函数的属性。

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;
Run Code Online (Sandbox Code Playgroud)

假设它在中myModule.js。然后,您可以执行以下操作:

const myModule = require('./myModule');
myModule(); // Prints: 'default!'
myModule.namedFunction1(); // Prints: '1!'
Run Code Online (Sandbox Code Playgroud)

  • 我假设有一个原因,但为什么不直接分配给 module.exports 呢?我尝试了一下,它似乎工作正常:`module.exports = defaultFunction; module.exports.namedFunction1 = namedFunction1;` (4认同)
  • @arichards如果这对你来说更容易/更好,那么这应该可行。如果我相当确定该函数在使用它的地方将被称为“myModule”,那么我也喜欢在定义它的地方将其称为“myModule”。但这只是我的偏好。 (2认同)

KJ *_*han 8

只需重新分配exportsmodule.exports

喜欢:

//name.js

const NameType = {
  foo: "bar",
};

function Name(name) {
  this.name = name;
}

module.exports = Name; // assign default export to Name
exports = module.exports; // re-assign exports to point it to the updated location.

exports.NameType = NameType; // now you can use named export as usual
Run Code Online (Sandbox Code Playgroud)

在另一个文件中,您可以像这样导入:

const Name = require("./name");
const { NameType } = require("./name");
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为默认情况 module = { exports: {} }下并且exports = module.exports

参考:CommonJs模块系统中“module.exports”和“exports”的区别