Yağızhan Y.
Yağızhan Y.

Reputation: 384

Defining modules in one file and requiring it in Node.js

I'm updating my code to include new packages so often and I have more than 100 files.

I want to make something like this,

File : dependencies.js :

const snekfetch = require("snekfetch");
const fs = require("fs");

It's very annoying to modify every file to add just a single package.

I'm trying to require the dependencies.js using this:

require("./dependencies.js")

But I see this in my console:

ReferenceError: snekfetch is not defined

Is there any way I can succeed?

Upvotes: 1

Views: 83

Answers (1)

sagar agarwal
sagar agarwal

Reputation: 142

I think you are not exporting the modules in dependencies.js dependencies.js should look like,

    const snekfetch = require("snekfetch");
    const fs = require("fs");
    module.exports = {
      "snekfetch": snekfetch,
      "fs": fs
    };

Then you should be able to import this file and use it like as follows,

    var dependencies = require('./dependencies.js');
    // dependencies.fs.readFile();

Although there are much better ways to handle your imports then just creating a simple file of dependencies. Have a look at this link.

Upvotes: 2

Related Questions