[英]How does require work?
I have 2 files in a folder called js. 我在名为js的文件夹中有2个文件。 I am using webpack.
我正在使用webpack。
js/app.js and js/login.es6. js / app.js和js / login.es6。
I'm trying to include the login from my app.js: 我正在尝试包括来自我的app.js的登录名:
require('login.es6') fails
require('./login.es6') works.
Any idea why? 知道为什么吗?
When you write require('login.es6')
node will look for a module named login.es6
in your node_modules. 当您编写
require('login.es6')
节点时, login.es6
在login.es6
中查找名为login.es6
的模块。
When you write require('./login.es6')
node understands that ./login.es6
is a relative path and will load your js/login.es6.js
file. 当您编写
require('./login.es6')
节点时,将了解./login.es6
是相对路径,并将加载您的js/login.es6.js
文件。
This is needed to distinguish between modules and local files. 这是区分模块和本地文件所必需的。 There may be a npm module called
login.es6
; 可能有一个名为
login.es6
的npm模块; this way you can reference both the module and your local file in your project. 这样,您可以在项目中同时引用模块和本地文件。
The node.js docs on require
are pretty nice and gives a good overview of how modules are prioritized when loaded. 所
require
的node.js文档非常不错,并且很好地概述了模块在加载时如何确定优先级。
The gist is, if you don't start the string with ./
, require
will first look for a core module, then recursively look in the node_modules
directory/-ies. 要点是,如果您不以
./
开头字符串,则require
将首先查找核心模块,然后递归查找node_modules
目录。 So it's normal to start require calls to local files with ./
. 因此,开始要求使用
./
调用本地文件是正常的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.