'requiring a directory rather than a js file
I come across a piece code like this in an index.js file:
exports = module.exports = require("./src")
Not sure what the exports = module.exports
bit means.
And not sure what it means to import an entire directory /src
.
Solution 1:[1]
TL;DR
These are solutions for your questions, from first to second (in order).
- Most likely setting the variable
exports
tomodule.exports
. - Importing a default file in the folder (e.g.
index.js
) if specified or not.
1. What does the exports
variable define?
From Dave Meehan, a few corrections made:
Comment #1
Your explanation of 1 is incorrect. If they were separate statements as illustrated, exports would equal the previous value of
module.exports
, andmodule.exports
would equal the return value ofrequire
. Chaining them together sets bothexports
andmodule.exports
to the value returned byrequire
. It's not clear why someone would want to do that, but they did.
Comment #2
We should be very careful in interpreting what the result might be in such a statement as its dependent on whether the variables
export
andmodule
(with/without property exports) already exists, and whether we are usingstrict
mode. There's a number of other SO posts that expand on "chaining assignment".
Note: I am also mildly confused on this line, so this is my educated guess. Feel free to correct me in the comments, or by editing my post.
Note: This solution is incorrect. Please see Dave Meehan's comments on corrections for this solution.
This line most likely can be also spread into multiple lines, like so.
exports = module.exports;
module.exports = require("./src");
Basically, it is just making a variable called exports
, and setting that to module.exports
.
This same thing can be done using object destructing too.
const { exports } = module;
This will simply get the exports
key from module
, and make a new variable called exports
.
2. How do you require
a folder?
Technically, Node isn't importing an entire folder. Basically, it is checking for a default file in the directory.
There are two cases in how Node.js will check for a file.
If the
main
property is defined inpackage.json
, it will look for that file in the/src
directory.{ "main": "app.js" }
If the
package.json
, was like that, for instance, then it would search for/src/app.js
.If the
main
property isn't defined inpackage.json
, then it will by default look for a file namedindex.js
. So, it would import/src/index.js
.
Summary
In summary, these are the solutions to your questions.
- Most likely setting the variable
exports
tomodule.exports
. - Importing a default file in the folder (e.g.
index.js
) if specified or not.
This should help clear your confusion.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |