DEV Community

Stephen Charles Weiss
Stephen Charles Weiss

Posted on • Originally published at stephencharlesweiss.com on

31 6

What Is `require.resolve` And How Does It Work?

In order to understand require.resolve, part of the Node API, we must first understand its context. Namely, the require module and how it fits within the realm of import/export and require/module.export of modules in Javascript.

At the top of many Javascript files, we import libraries to use (e.g., Lodash, React, etc.) and / or other local files that export modules (e.g., a react component or a utility function).

For example, if we wanted to import modules to use, we may write something like the following:

import React from 'react'; // a default exported module from a library
import * as _ from 'lodash'; // a name space for all exported modules from a library
import { Link } from 'gatsby'; // a named exported module from a library
import Layout from '../components/Layout'; // a local default exported module

As I noted previously in my primer for imports / exports, these will all need to be transpiled as no JS engine yet supports imports (but that’s what Babel, Webpack, etc. are for). ¹

Alternatively, we could write the following:

var React = require('react');
var _ = require('lodash')
var { Link } = require('gatsby')
var Layout = require('../components/Layout')

Sometimes, however, we just want the path to a file. This is more commonly the case on the server side. In the past, I’ve used path.join(__dirname, "module-i-am-looking-for") to get the path using node’s path module.

var fs = require('fs');
var path = require("path");

// "__dirname" provides the absolute path to the current module directory.
console.log( fs.readFileSync (path.join( __dirname, "module-i-am-looking-for.js") ) );

There’s an alternative, however. It’s the require.resolve API. According to the Node documentation), the require.resolve “use(es) the internal require() machinery to look up the location of a module, but rather than loading the module, just return(s) the resolved filename.” ²

var fs = require('fs');

// "__dirname" provides the absolute path to the current module directory.
console.log( fs.readFileSync (require.resolve("module-i-am-looking-for.js") ) );

As Ben Nadel notes, there’s inherently more overhead in this approach, but from a readability perspective, there are some significant wins here.³

Resources

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs