我的 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/