runners3431
runners3431

Reputation: 1455

How does require work?

I have 2 files in a folder called js. I am using webpack.

js/app.js and js/login.es6.

I'm trying to include the login from my app.js:

require('login.es6') fails
require('./login.es6') works. 

Any idea why?

Upvotes: 0

Views: 94

Answers (3)

fredrikekelund
fredrikekelund

Reputation: 2095

The node.js docs on require are pretty nice and gives a good overview of how modules are prioritized when loaded.

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. So it's normal to start require calls to local files with ./.

Upvotes: 0

Chris54721
Chris54721

Reputation: 136

This is needed to distinguish between modules and local files. There may be a npm module called login.es6; this way you can reference both the module and your local file in your project.

Upvotes: 0

MatthieuLemoine
MatthieuLemoine

Reputation: 706

When you write require('login.es6') node will look for a module named login.es6 in your node_modules.

When you write require('./login.es6') node understands that ./login.es6 is a relative path and will load your js/login.es6.js file.

Upvotes: 1

Related Questions