【问题标题】:node.js local modules :cannot find module errornode.js 本地模块:找不到模块错误
【发布时间】:2018-08-05 22:28:14
【问题描述】:

我正在尝试在我的应用程序中实现本地模块

1.项目根文件夹我创建了一个名为test的文件夹和一个名为index.js的文件

      module.exports  = {

     myFunction:function(){
       console.log('ok');
     }
}

2.在根文件夹package.json中添加以下内容

"dependencies": { 
    "test-module": "file:test"
  }

3.当我尝试在app.js 中导入var module = require('test-module'); 时出现此错误

找不到模块'test-module'

【问题讨论】:

  • 我现在遇到了同样的问题。这很奇怪,因为该模块位于node_modules 文件夹中。不知道为什么。
  • 我认为您错过了 package.jsontest-module 包中的 main 部分。

标签: javascript node.js express npm module


【解决方案1】:

您可以提供包含包的本地目录的路径

{
  "name": "baz",
  "dependencies": {
    "bar": "file:../foo/bar"
  }
}

并执行 npm install -snpm install --save reference

【讨论】:

    【解决方案2】:

    确保您的test 文件夹有一个package.json

    test/package.json 应该有一个 "name" 字段,其值为 "test-module"(即,与根 package.json 中的依赖项同名。

    我的文件:

    test/package.json

    {
      "name": "test-module",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }
    

    test/index.js

    module.exports = {
      t:() => console.log('t')
    };
    

    package.json

    {
      "name": "t",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "test-module": "file:test"
      }
    }
    

    app.js

    t = require('test-module');
    t.t();
    

    这对我有用。

    【讨论】:

    • 是的,我有同样的
    • 我需要安装其他软件包吗??
    • 不,您不需要任何其他软件包。我完全尝试了您的代码,它对我有用。我遇到的唯一问题是名称字段不同。
    • 我更新了答案以显示示例中的所有文件。你能告诉我们node_modules文件夹中的文件结构吗?
    • 我的test 文件夹不在node_modules 文件夹中,我需要手动添加吗??
    【解决方案3】:

    要添加@Blaze 答案,如果您按照steps(本地路径)安装本地模块,它将为您整理 package.json 中的本地依赖项:

    npm i ./test --save
    

    这将在根package.json 中的dependencies 中生成正确的本地依赖项:

    "test-module": "file:test"
    

    假设test-module 是本地部门package.json 中的名称。

    它应该是这样的:

    【讨论】:

    • 现在找不到模块错误消失了,但我得到另一个错误app.set不是函数
    • @iambatman:那将是一个完全不同的问题 :) 我建议你为那个问题打开另一个问题。
    • 如果我删除了导入,它就消失了
    • 你的测试模块上有什么?听起来有一个app.set 不在原始问题中
    • 它包含一个 index.js 文件,其中包含我在问题中包含的函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 2016-05-11
    • 2013-02-03
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多