簡體   English   中英

本地模塊node.js:除index.js之外,無法加載其他文件

[英]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"
}

由於hellohello-module的文件,因此需要將其作為requirepath傳遞。 做:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM