[英]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.