Skip to content

Instantly share code, notes, and snippets.

@daleyjem
Last active September 10, 2024 02:13
Show Gist options
  • Save daleyjem/0f38f561a4e91e58eba580889f38330f to your computer and use it in GitHub Desktop.
Save daleyjem/0f38f561a4e91e58eba580889f38330f to your computer and use it in GitHub Desktop.
Explanation of a "deep import"

Deep Imports

Description

A "deep import" is simply an ESM import that goes deeper than the package root:

import thingA from 'my-package-name/src/components/thingA'
import thingB from '@my-namespace/my-package-name/src/components/thingA'

A namespaced package does not necessitate a deep import if the package name (package.json:name key) contains a slash:

import thingA from '@my-namespace/my-package-name'

Relative imports (./path/to/module) are also not considered deep imports, in fact it might be considered bad practice to "shallow import" an exported module from one's own package by it's package.json:main key location (i.e. src/index.js) as this can often cause circular dependencies.

Why deep imports can be a problem

Package bundling

Package bundlers are often used to transpile and condense a project to a distributive, single-file version (i.e. dist/bundle.js). Other packages that try to deep import from such packages experience errors, as the directory structure from src may often not be maintained or even included in the published package.

Unintended imports and directory changes

A developer might deep import a module from a package when it was not intended to be used outside of the scope of that package. Your changing of the name of an internally-used export or your package's directory structure should not require a major version (breaking change) update for a module that was only intended to be consumed internally.

The proposal

Modules meant to be imported-from by another package should be exported from the package's entry file (i.e. src/index.js) and deep imports should not be used unless otherwise prescribed by the package developer.

@AlbertMarashi
Copy link

Great resource!

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