find-import
TypeScript icon, indicating that this package has built-in type declarations

1.0.8 • Public • Published

find-import

Find and load first instance of js/json in parent directories.

npm package License

Contents

Introduction

Load the first instance of a found module.

Optionally specify depth preference to prefer "top-most" packages.

Supports .json, .cjs, .mjs, and .js.

Returns the path and contents of the found module.

Install

npm i find-import

Example

Given file structure

/
└─┬ root
  ├── my-file.cjs // module.exports = { abc: 123 }
  └─┬ my-package
    └── my-file.json // { "foo": "bar" }
// cwd = /root/my-package
import { findImport } from 'find-import';

let found;

found = await findImport(['my-file.cjs', 'my-file.json']);
found.content // { foo: 'bar' }
found.filePath // /root/my-package/my-file.json

found = await findImport(['my-file.cjs', 'my-file.json'], {
    direction: 'down',
});
found.content // { abc: 123 }
found.filePath // /root/my-file.cjs

found = await findImport(['my-file.cjs', 'my-file.json'], {
    direction: 'down',
    startAt: '/root/my-package',
});
found.filePath // /root/my-package/my-file.json


found = await findImport(['my-file.cjs', 'my-file.json'], {
    cwd: '/root',
});
found.filePath // /root/my-package/my-file.cjs

Usage

find-import is an ESM module. That means it must be imported. To load from a CJS module, use dynamic import const { findImport } = await import('find-import');.

API

findImport(fileNames, options?)

Finds first instance of matching module, and loads. Returns file path to module and content.

Note that content is the result of a dynamic import() call. If accessing the default content, it may be necessary/convenient to extract that content. See default-import for a potential solution.

fileNames

string or array of strings

List of file names to search for in each directory.

options

  • cwd

    • Type: string or URL
    • optional, defaults to process.cwd()
    • Directory to use as base directory.
    • See parse-cwd.
  • direction

    • 'up'(default) or 'down'
    • direction to search for files.
      • 'up' indicates /foo/bar -> /foo -> /
      • 'down' is opposite, / -> /foo -> /foo/bar
  • startAt

    • Type: string or URL
    • optional, defaults to /
    • Top-most "root" directory to limit search.

Readme

Keywords

Package Sidebar

Install

npm i find-import

Weekly Downloads

116

Version

1.0.8

License

MIT

Unpacked Size

7.52 kB

Total Files

6

Last publish

Collaborators

  • jacobley