Importing a GLOBAL module like require() in PHP

Hi there! awesome courses, I’m learning a lot!

I was wondering if it is possible to export and import modules globally in one file (let’s say the entry point) that’ll be available for the entire project.

For example, let’s say I’ve created a fetch API wrapper module called MyFetch.js, and I import it in the entry point index.js. In the index.js, I also import many other modules, and I want to use that MyFetch module in them, without importing it again (because I’ve already imported it in the entry point).

Basically, is there anything like require in PHP where you can require a file in the runtime and that file’s functionality will be available everywhere?

Yes, there are two ways to accomplish this.

  1. use “global” object.

    global.express = require("express");
    
  2. modifying the Node.js runtime

I don’t want to dive too deep into the second method becaus that will be extremely complicated.

Moreover, you should understand that both of these two methods are very discouraged and you should avoid using them, especially in production environments.