简体   繁体   English

如何在js中返回匿名函数?

[英]How to return an anonymous function in js?

I have the following code in my node project. 我的节点项目中有以下代码。

import Joi from 'joi';

module.exports = function() {
    Joi.objectId = require('joi-objectid')(Joi);
}

When I try to 当我尝试

export default function() {

it doesn't work. 它不起作用。 How can I export this function using export rather than using es5 module.exports? 如何使用导出而不是使用es5 module.exports导出此函数?

给它命名或将其分配给变量:

export default function myFunc() {...}

You can write like this 你可以写这样的

import Joi from 'joi';       
  const myFunc = () => {
    Joi.objectId = require('joi-objectid')(Joi);
  }
export default myFunc; 

Since your environment is "nodejs", you probably are not using any transpilers. 由于您的环境是“nodejs”,您可能没有使用任何转发器。 This mean you have to follow nodejs extensions to allow es6 modules. 这意味着您必须遵循nodejs扩展以允许es6模块。

To enable es6 modules, you first need to change the extension of your script to mjs , then start nodejs using node --experimental-modules index.mjs 要启用es6模块,首先需要将脚本的扩展名更改为mjs ,然后使用node --experimental-modules index.mjs启动node --experimental-modules index.mjs

See also https://nodejs.org/api/esm.html 另见https://nodejs.org/api/esm.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM