繁体   English   中英

node.js 本地模块:找不到模块错误

[英]node.js local modules :cannot find module error

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

1.项目根文件夹我创建了一个名为test的文件夹,其中包含一个名为index.js的文件

      module.exports  = {

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

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

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

3.当我尝试导入var module = require('test-module'); app.js我收到这个错误

找不到模块“测试模块”

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

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

并执行npm install -snpm install --save参考

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

test/package.json应该有一个值为"test-module""name"字段(即,与根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();

这对我有用。

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

npm i ./test --save

这将产生在正确的地方依赖项dependenciespackage.json

"test-module": "file:test"

假设test-module是本地 dep package.json的名称。

它应该是这样的:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM