繁体   English   中英

如何在 JavaScript 中正确使用模块导出

[英]How To Use Module Exports Properly In JavaScript

我刚开始学习 JS,当我尝试使用此代码在名为 function_module.js 的文件中导出一个简单的 function

module.exports.squareFunction = function(nb){
return nb * nb ;
}

在同一目录中的其他文件中,我尝试使用此代码导入 function

const importedfun = require('./function_module.js');
console.log(importedfun(5));

我收到了这个错误

JavaScript\CodeAcademy\module\test_module.js:2
console.log(importedfun(5));
        ^

TypeError: importedfun is not a function
at Object.<anonymous>

谁能告诉我我的错是什么?

通过执行module.exports.squareFunction ,您可以使用commonjs语法创建named export 您可以使用方括号{nameOfYourExportedFunction}在另一个模块中要求它,或者改为执行默认导出。

命名导出

module.exports.squareFunction = function(nb){
    return nb * nb ;
}

//////

// Notice the brackets wrapping the function
const {squareFunction} = require('./function_module.js');
console.log(squareFunction(5));

默认导出

module.exports = function(nb){
    return nb * nb ;
}

//////

// You can name it however you want since it will refer to the default export
const importedFun = require('./function_module.js');
console.log(importedfun(5));

暂无
暂无

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

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