load-from-cwd-or-npm

3.0.4 • Public • Published

load-from-cwd-or-npm

npm version Build Status Coverage Status

Load a module from either CWD or npm CLI directory

const loadFromCwdOrNpm = require('load-from-cwd-or-npm');
 
// $ npm ls validate-npm-package-name
// > └── (empty)
 
(async () => {
  require('validate-npm-package-name'); // throws a `MODULE_NOT_FOUND` error
  const RegistryClient = await loadFromCwdOrNpm('validate-npm-package-name'); // doesn't throw
})();

Installation

Use npm.

npm install load-from-cwd-or-npm

API

const loadFromCwdOrNpm = require('load-from-cwd-or-npm');

loadFromCwdOrNpm(moduleId)

moduleId: string (a module ID without path separators (/, \\))
Return: Promise<any>

It loads a module with the given module ID from either of these two directories:

  1. node_modules in the current working directory
  2. node_modules in the directory where npm CLI is installed

If the module ins't installed in CWD but included in the npm CLI dependencies, it loads the module from npm CLI directory.

// $ npm ls nopt
// > └── (empty)
 
(async () => {
  const nopt = await loadFromCwdOrNpm('nopt'); //=> {[Function: nopt], clean: [Function: clean] ...}
})();

If the module ins't included in the npm CLI dependencies but installed in CWD, it loads the module from CWD.

// $ npm ls eslint
// > └── eslint@4.11.0
 
(async () => {
  // npm doesn't depend on `eslint` module.
  const eslint = await loadFromCwdOrNpm('eslint'); //=> {linter: EventEmitter { ... }, ...}
})();

If the module exists in both directories, it compares their package versions and loads the newer one.

// $ npm ls rimraf
// > └── rimraf@1.0.0
 
(async () => {
  // Loaded from npm CLI directory because the CWD version is older
  const rimraf = await loadFromCwdOrNpm('rimraf');
})();

The returned promise will be fulfilled with the loaded module, or rejected when it fails to find the module from either directories.

License

ISC License © 2017 - 2018 Shinnosuke Watanabe

Dependencies (4)

Dev Dependencies (13)

Package Sidebar

Install

npm i load-from-cwd-or-npm

Weekly Downloads

859

Version

3.0.4

License

ISC

Unpacked Size

7.94 kB

Total Files

4

Last publish

Collaborators

  • shinnn