javascript - 如何在 Node.js 项目子文件夹中使用 require()

标签 javascript node.js require

我的 Node.js 项目的目录结构如下:

  • 服务器.js
  • package.json
  • ...
  • 公开
    • app.js
    • index.html

require() 的调用在 server.js 中工作正常,但是当我尝试在 app.js 中请求包时,抛出 ReferenceError:

 require is not defined at app.js:1

如何从不在我的项目全局范围内的文件中获取 Node 模块?

最佳答案

使用类似这样的东西 var db = require('../model/db');

它基本上意味着../从当前目录向上移动一步,然后进入模型,然后进入数据库。

您需要使用它来向上移动目录结构,然后在 require 中使用它。

node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().

require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().

为了使用 Require Js 。只要按照这个link

关于javascript - 如何在 Node.js 项目子文件夹中使用 require(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45742384/

相关文章:

javascript - 使用 Angular JS 组件创建表单容器

javascript - 字母字符串排序

javascript - npm link gulp 之后任务 'default' 不在你的 gulpfile 中

Ruby - 要求加载错误

javascript - 导出 Node.js 模块

javascript - 使用 Javascript : How to unlock a partially locked layer? 的 Photoshop 脚本

javascript - 自定义 JQuery 克隆行属性

javascript - Mongoose - 当从集合中返回所有项目(没有搜索参数)时,从集合中返回的项目不包含其 mongo _id

javascript - 你如何运行多个 grunt scripts.postinstall?

javascript - 如何在 Node.js 应用程序中需要额外的模块