@ombro/is-main
v0.1.1
Published
Check if the current module is an entry module for ESM
Downloads
64
Readme
@ombro/is-main
Check if the current module is an entry module for ESM, usually useful in command line scripts.
Install
$ npm install @ombro/is-main
Usage
import { isMain } from '@ombro/is-main'
if (isMain(import.meta)) {
// ...
}
If you're using CommonJS modules, then judge directly:
if (require.main === module) {
// ...
}
Example
Suppose we want to create two tasks, clean
and build
. Before build
, we will pass a parameter --clean
to determine whether clean
needs to be performed first, and the clean
task can also be executed separately
# Only clean
node clean.js
# Only build
node build.js
# Clean and build
node build.js --clean
clean.js
:
import { isMain } from '@ombro/is-main'
export function clean() {
// clean...
}
// Executed only when the clean.js is an entry module
if (isMain(import.meta)) {
clean()
}
build.js
:
import { isMain } from '@ombro/is-main'
import { clean } from './clean.js'
export function build() {
// build...
}
// Executed only when the build.js is an entry module
if (isMain(import.meta)) {
process.argv.includes('--clean') && clean()
build()
}
License
MIT