Skip to content
pkg-types / 3.0.0

pkg-types 3.0.0

Install from the command line:
Learn more about npm packages
$ npm install @flex-development/pkg-types@3.0.0
Install via package.json:
"@flex-development/pkg-types": "3.0.0"

About this version

pkg-types

github release npm module type: esm license conventional commits typescript vitest yarn

TypeScript definitions for package.json

Contents

What is this?

This package contains TypeScript definitions for package.json files and values used in package.json files.

Install

yarn add @flex-development/pkg-types

From Git:

yarn add @flex-development/pkg-types@flex-development/pkg-types
See Git - Protocols | Yarn  for details on requesting a specific branch, commit, or tag.

Use

import type { PackageJson } from '@flex-development/pkg-types'
import fs from 'node:fs'
import path from 'node:path'

/**
 * Enables or disables [`type`][1] in `package.json`.
 *
 * [1]: https://nodejs.org/api/packages.html#type
 *
 * @example
 *  toggle()
 * @example
 *  toggle('off')
 * @example
 *  toggle('on')
 *
 * @param {'off' | 'on'} [command] - Toggle command
 * @return {void} Nothing when complete
 */
function toggle(command?: 'off' | 'on'): void {
  // see: https://yarnpkg.com/advanced/lifecycle-scripts#environment-variables
  const { npm_package_json = 'package.json' } = process.env

  /**
   * Absolute path to `package.json`.
   *
   * @const {string} pkgfile
   */
  const pkgfile: string = path.resolve(npm_package_json)

  /**
   * `package.json` data.
   *
   * @var {PackageJson} pkg
   */
  let pkg: PackageJson = JSON.parse(fs.readFileSync(pkgfile, 'utf8'))

  // toggle package type
  pkg = Object.keys(pkg).reduce<PackageJson>((acc, key) => {
    const [, type, prefix = ''] = /^((#?)type)$/.exec(key) ?? []

    if (type) {
      key = command
        ? `${command === 'off' ? '#' : ''}type`
        : prefix
        ? type.replace(new RegExp('^' + prefix), '')
        : '#' + type

      acc[key] = pkg[type]!
    } else {
      acc[key] = pkg[key]!
    }

    return acc
  }, {})

  // rewrite package.json
  return void fs.writeFileSync(pkgfile, JSON.stringify(pkg, null, 2) + '\n')
}

export default toggle

Need this functionality? See toggle-pkg-type 😊

API

Interfaces

Types

Related

Contribute

See CONTRIBUTING.md.

Details


Assets

  • pkg-types-3.0.0.tgz

Download activity

  • Total downloads 6,342
  • Last 30 days 701
  • Last week 225
  • Today 30

Recent versions

View all