In various JavaScript environments, the way we reference or import files relative to the current script can differ. Below, we'll walk through methods to resolve relative file paths in five environments: CommonJS (CJS) in Node.js, Web Browsers, ECMAScript Modules (ESM) in Node.js, Deno, and Browsers using bundlers (like webpack or Parcel).

1. CommonJS (CJS) in Node.js

CommonJS is the traditional module system used in Node.js.

Methods to Resolve Relative Paths:

  • Using : This global variable provides the directory path of the current module.
  • Using : This method resolves the module's path, similar to how would load the module.
  • Using : Returns the current working directory of the Node.js process. Be cautious when using this, as it gives the directory from where Node.js was invoked, not the script's location.

2. Web Browsers

Traditionally, web browsers don't have built-in module systems like Node.js. Paths are typically resolved relative to the HTML document.

Methods to Resolve Relative Paths:

  • Using tags: The browser will fetch and execute the script relative to the HTML file's location.
  • Using the object: In modern browser APIs, this can be helpful.

3. ECMAScript Modules (ESM) in Node.js

With the growing adoption of ESM, Node.js introduced native support for ES modules.

Methods to Resolve Relative Paths:

  • Using : In ESM, isn't available. Instead, you can use .

4. Deno

Deno is a JavaScript runtime similar to Node.js but with a focus on security and modern features. It uses ES modules by default.

Methods to Resolve Relative Paths:

  • Using : Just like ESM in Node.js, you can use this in Deno.

5. Browsers with Bundlers (e.g., webpack, Parcel)

When using bundlers, paths are typically abstracted, and the actual resolution is handled by the bundler itself.

Methods to Resolve Relative Paths:

  • Using or : Bundlers intercept these calls and replace them with their own resolution logic.

Conclusion

Depending on the JavaScript environment and module system you're working with, there are various methods to resolve relative file paths. Always ensure you're using the correct method for the environment to avoid resolution errors and ensure portability.