0.3.0 โข Published 10 months ago
import-local-or-npx v0.3.0
Usage
npm i import-local-or-npximport { importLocalOrNpx } from "import-local-or-npx";
await importLocalOrNpx("create-typescript-app");importLocalOrNpx allows you to import from a path to a CJS or ESM module, or 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
Use this project if you'd like to import a package that may or may not exist locally, and if it doesn't yet exist, should be installed in a global cache.
Options
importLocalOrNpx takes in up two to arguments:
specifier: string(required): Where to import from, which can be either:- A local path to a package on disk, such as a relative
"../path/to/directory" - A package name, such as
"create-typescript-app"
- A local path to a package on disk, such as a relative
options(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-resolvesucceeded - npx import
{ kind: "npx", resolved: object }: failing that, if importing the specifier withimportNpxsucceeded - Failure
{ kind: "failure", local: Error; npx: Error }: if both of those failed or were canceled
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.
Development
See .github/CONTRIBUTING.md, then .github/DEVELOPMENT.md.
Thanks! ๐
Contributors
๐ This package was templated with
create-typescript-appusing thecreateengine.