pkg-types
package.json 和 tsconfig.json 的 Node.js 实用工具和 TypeScript 定义
适用于
package.json
和tsconfig.json
的 Node.js 工具和 TypeScript 定义
\⍩⃝/
安装
# npm
npm i pkg-types
# yarn
yarn add pkg-types
# pnpm
pnpm add pkg-types
用法
readPackageJSON
import { readPackageJSON } from 'pkg-types'
const localPackageJson = await readPackageJSON()
// or
const packageJson = await readPackageJSON('/fully/resolved/path/to/folder')
writePackageJSON
import { writePackageJSON } from 'pkg-types'
await writePackageJSON('path/to/package.json', pkg)
resolvePackageJSON
import { resolvePackageJSON } from 'pkg-types'
const filename = await resolvePackageJSON()
// or
const packageJson = await resolvePackageJSON('/fully/resolved/path/to/folder')
readTSConfig
import { readTSConfig } from 'pkg-types'
const tsconfig = await readTSConfig()
// or
const tsconfig = await readTSConfig('/fully/resolved/path/to/folder')
writeTSConfig
import { writeTSConfig } from 'pkg-types'
await writeTSConfig('path/to/tsconfig.json', tsconfig)
resolveTSConfig
import { resolveTSConfig } from 'pkg-types'
const filename = await resolveTSConfig()
// or
const tsconfig = await resolveTSConfig('/fully/resolved/path/to/folder')
resolveFile
import { resolveFile } from 'pkg-types'
const filename = await resolveFile('README.md', {
startingFrom: id,
rootPattern: /^node_modules$/,
matcher: filename => filename.endsWith('.md'),
})
resolveLockFile
查找锁定文件(yarn.lock
, package-lock.json
, pnpm-lock.yaml
, npm-shrinkwrap.json
)的路径,否则抛出错误。
import { resolveLockFile } from 'pkg-types'
const lockfile = await resolveLockFile('.')
findWorkspaceDir
尝试按以下顺序检测工作区目录:
- 最近的
.git
目录 - 最远的锁定文件
- 最远的
package.json
文件
如果失败,则抛出错误。
import { findWorkspaceDir } from 'pkg-types'
const workspaceDir = await findWorkspaceDir('.')
类型
注意: 为了使类型生效,你需要将 typescript
安装为开发依赖。
你可以直接使用类型化接口
import type { TSConfig, PackageJSON } from 'pkg-types'
你也可以使用定义工具来支持类型,以便在普通 .js
文件中使用并在 IDE 中进行自动补全。
import type { definePackageJSON } from 'pkg-types'
const pkg = definePackageJSON({})
import type { defineTSConfig } from 'pkg-types'
const pkg = defineTSConfig({})
替代方案
许可
MIT - 倾心制作 💛