[英]How to get node into other .js files other than index.js in electron
[英]local modules node.js :can't load files other than index.js
我正在嘗試在我的express js應用程序中學習本地模塊設置。
在我的項目文件夾中創建了test-module
文件夾,其中包含兩個文件
1)index.js
module.exports = {
indexfunc:function(){
console.log('ok from index');
}
}
2)hello.js。
module.exports = {
helloFunc:function(){
console.log('ok from hello');
}
}
將此模塊導入app.js
文件
var mymodule = require('hello-module');
console.log(mymodule);
output:{ indexfunc: [Function: indexfunc] }
但這將返回console.log(require('hello-module').hello)
undefined
。
該模塊的package.json
{
"name": "hello-module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
由於hello
是hello-module
的文件,因此需要將其作為require
的path
傳遞。 做:
console.log(require('hello-module/hello'))
通過做 :
console.log(require('hello-module').hello)
您正在打印由index.js
導出的hello
屬性
除了@Ayush答案之外,如果您的目標是從模塊文件夾中的其他文件執行代碼,則可以像這樣導出引用:
//index.js
const helloModule = require('./hello');
module.exports = {
hello: helloModule,
indexfunc:function(){
console.log('ok from index');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.