@flex-development/pkg-types
TypeScript icon, indicating that this package has built-in type declarations

3.0.0 • Public • Published

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.

Package Sidebar

Install

npm i @flex-development/pkg-types

Weekly Downloads

1

Version

3.0.0

License

BSD-3-Clause

Unpacked Size

89.3 kB

Total Files

39

Last publish

Collaborators

  • unicornware