1.0.14 • Published 4 months ago

find-import v1.0.14

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

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.
1.0.14

4 months ago

1.0.13

5 months ago

1.0.12

5 months ago

1.0.11

8 months ago

1.0.10

8 months ago

1.0.9

8 months ago

1.0.8

10 months ago

1.0.7

10 months ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago