Skip to content

Instantly share code, notes, and snippets.

@MattGoldwater
Last active December 17, 2019 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattGoldwater/78f89ea93b9f1dfc19d3440e172cfa49 to your computer and use it in GitHub Desktop.
Save MattGoldwater/78f89ea93b9f1dfc19d3440e172cfa49 to your computer and use it in GitHub Desktop.
Explanation of node's module resolution system

When you import a module, Node first checks to see if you imported a core node module such as fs or http.

import fs from 'fs';

Then it checks to see if you've entered a path to a file. Lets pretend we have a file named app.js.

import App from './app';

Then it checks to see if the term you imported is in the nearest parent node_modules folder. This will occur if you import a bare specifier, a file or folder name without a listed path, such as react.

import React from 'react';

Node looks in the current file's parent folder's direct children for a node_modules folder that contains a direct child folder with the name of the bare specifier you imported. If it doesn't find that, it proceeds to look for a node_modules folder in its grandparent directory and continues until it can't find a parent directory.

If you're reading this, you use a package manager and you haven't used yarn pnp, you're probably used to seeing a node_modules folder in your apps root directory. Therefore, your app will work because when you import a package node will eventually check your root directory and find the package name you entered in your import statement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment