# es-main

> Test if an ES module is run directly (require.main replacement)

Latest version **1.4.0** (published 2025-08-10) · MIT license · 0 weekly downloads

## Install

```sh
npm install es-main
pnpm add es-main
yarn add es-main
bun add es-main
```

## Health

**Score 50/100 (C)** — status: stable.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: stale.

## Facts

| | |
|---|---|
| Version | 1.4.0 |
| Published | 2025-08-10 |
| First published | 2020-02-19 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 4.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 95 |
| Maintainers | tschaub |
| Keywords | require.main, process.mainModule, modules, import.meta.main |

## Links

- npm: https://www.npmjs.com/package/es-main
- Repository: https://github.com/tschaub/es-main
- Homepage: https://github.com/tschaub/es-main#readme
- Issues: https://github.com/tschaub/es-main/issues
- npm.io page: https://npm.io/package/es-main

## Recent versions

- 1.4.0 (latest) — 2025-08-10
- 1.3.0 — 2023-09-02
- 1.2.0 — 2022-06-28
- 1.1.1 — 2022-06-28
- 1.1.0 — 2022-06-28
- 1.0.2 — 2020-02-20
- 1.0.1 — 2020-02-19
- 1.0.0 — 2020-02-19

## README

# es-main

Test if an [ES module](https://nodejs.org/api/esm.html) is run directly with Node.js.  Acts as a replacement for `require.main`.

> [!NOTE]
> If you are using Node.js versions newer than `22.18.0` or `24.2.0`, you should use the built-in [`import.meta.main`](https://nodejs.org/docs/latest/api/esm.html#importmetamain) instead of this module.

## use

```js
import esMain from 'es-main';

if (esMain(import.meta)) {
  // Module run directly.
}
```

## why?

It can be useful to have a module that is both imported from other modules and run directly.  With CommonJS, it is possible to have a top-level condition that checks if a script run directly like this:

```js
if (require.main === module) {
  // Do something special.
}
```

With ES modules in Node.js, `require.main` is [not available](https://nodejs.org/dist/latest-v14.x/docs/api/esm.html#esm_no_require_exports_module_exports_filename_dirname).  Other alternatives like `process.mainModule` and `module.parent` are also not defined for ES modules.  In the future, there may be [an alternative way](https://github.com/nodejs/modules/issues/274) to do this check (e.g. `import.meta.main` or a special `main` export).  Until then, this package provides a workaround.

---
_Source: https://npm.io/package/es-main · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
