1.0.3 • Published 1 year ago

get-module-pkg v1.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

Get your module's package.json without importing it

If I should maintain this repo, please ⭐️

DM me on Twitter if you have questions or suggestions.


Rather than hardcoding your module's version number (and then forgetting to update it when you release a new version), you can read it from your package.json file. This is useful for things like outputting the version for your CLI application.

Why not just import your package.json? Importing your package.json can break your project's structure when using TypeScript if package.json is outside of your source folder.

Installation

npm install get-module-pkg
yarn add get-module-pkg

Usage

PackageJSON

Each function takes a single string argument, which is the path to any file in the module you want to get the package.json for. This is usually import.meta.url or __filename for CommonJS.

import { getModulePkg, getModulePkgSync } from "get-module-pkg";

// Async
const pkg = await getModulePkg(import.meta.url);
console.log(pkg.name);

// Sync
const pkg = getModulePkgSync(import.meta.url);
console.log(pkg.name);

Version

You can also get the version directly:

import { getModuleVersion, getModuleVersionSync } from "get-module-pkg";

// Async
const version = await getModuleVersion(import.meta.url);
console.log(version);

// Sync
const version = getModuleVersionSync(import.meta.url);
console.log(version);

Types

import { PackageJSON } from "get-module-pkg";
  • find-up: Find a file or directory by walking up parent directories
  • read-json-safe: Read objects from JSON files without try catch.
  • types-pkg-json: Type checking for package.json
  • @types/node: TypeScript definitions for Node.js
  • eslint: An AST-based pattern checker for JavaScript.
  • eslint-config-bob: ESLint configuration for packages built with @bconnorwhite/bob
  • typescript: TypeScript is a language for application scale JavaScript development

MIT