【问题标题】:local modules node.js :can't load files other than index.js本地模块 node.js :无法加载 index.js 以外的文件
【发布时间】:2018-02-27 15:11:51
【问题描述】:

我正在尝试在我的 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"
}

【问题讨论】:

    标签: javascript node.js express module


    【解决方案1】:

    由于hellohello-module 中的一个文件,您需要将其作为path 传递给require。做:

    console.log(require('hello-module/hello'))
    

    通过这样做:

    console.log(require('hello-module').hello)
    

    您正在打印由index.js 导出的hello 属性

    【讨论】:

    【解决方案2】:

    除了@Ayush 的回答,如果您的目标是从模块文件夹中的其他文件执行代码,您可以像这样导出引用:

    //index.js
    
    const helloModule = require('./hello');
    
    module.exports = {
          hello: helloModule,
          indexfunc:function(){
           console.log('ok from index');
         }
    }
    

    【讨论】:

    猜你喜欢
    • 2013-07-23
    • 2020-11-12
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多