import-local-or-npx
v0.1.0
Published
Imports a local package or one installed from npx. ๐
Downloads
19,997
Readme
Usage
npm i import-local-or-npx
import { importLocalOrNpx } from "import-local-or-npx";
await importLocalOrNpx("create-typescript-app");
Options
importLocalOrNpx
takes in up two to arguments:
specifier: string
(required): Where to import fromoptions
(optional): any of:importer
: an asynchronous function to use instead ofimport()
logger
: a logger function to pass tonpxImport
import { importLocalOrNpx } from "import-local-or-npx";
await importLocalOrNpx("../create-typescript-app", {
importer: async (specifier) => await import(specifier),
logger: (message) => console.log(message),
});
Returned Value
importLocalOrNpx
returns a Promise for an object satisfying one of three possible types:
- Local import
{ kind: "local", resolved: object }
: if importing the specifier withawait import()
andenhanced-resolve
succeeded - npx import
{ kind: "npx", resolved: object }
: failing that, if importing the specifier withimportNpx
succeeded - Failure
{ kind: "failure", local: Error; npx: Error }
: if both of those failed
import { importLocalOrNpx } from "import-local-or-npx";
const imported = await importLocalOrNpx("../create-typescript-app");
if (imported.kind === "failure") {
console.error("Could not import...");
console.error(" - Error from local import", imported.local);
console.error(" - Error from npx import", imported.npx);
} else {
console.log("Yay! Imported from:", imported.kind);
console.log(imported.resolved);
}
See src/types.ts
for specifics.
Why?
importLocalOrNpx
allows you to import from a path to a CJS or ESM module, a package name that will be installed with npx.
It's essentially a coordinating wrapper around:
enhanced-resolve
: Used withawait import()
to attempt to load the specifier from a local path if possiblenpx-import
: If the package can't be found locally, it will be installed to your global system npx cache
Development
See .github/CONTRIBUTING.md
, then .github/DEVELOPMENT.md
.
Thanks! ๐
Contributors
๐ This package was templated with
create-typescript-app
using thecreate
engine.