Skip to content

Commit

Permalink
feat(pack): impl usePackageJsonPlugin plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
yarastqt committed Jun 22, 2021
1 parent 2ad5610 commit 69789db
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
14 changes: 14 additions & 0 deletions packages/pack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,20 @@ type Options = {
function useTypeScriptPlugin(options: Options): TypeScriptPlugin
```

### PackageJsonPlugin

A plugin that copy package.json and modify content. _(Run at `onFinish` step)._

#### Usage

```js
const { usePackageJsonPlugin } = require('@bem-react/pack/lib/plugins/PackageJsonPlugin')
usePackageJsonPlugin({
scripts: {},
})
```

## 🏗 Write own plugin

The plugin can perform an action on one of the available hook `onBeforeRun`, `onRun` and `onAfterRun`.
Expand Down
30 changes: 30 additions & 0 deletions packages/pack/src/plugins/PackageJsonPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { existsSync, writeFileSync } from 'fs-extra'
import { resolve } from 'path'
import { Plugin, OnDone, HookOptions } from '../interfaces'
import { mark } from '../debug'

type Overrides = Record<string, any>

export class PackageJsonPlugin implements Plugin {
name = 'PackageJsonPlugin'

constructor(private overrides: Overrides) {
mark('PackageJsonPlugin::constructor')
}

async onFinish(done: OnDone, { context, output }: HookOptions) {
mark('PackageJsonPlugin::onFinish(start)')
if (!existsSync(resolve(context, 'package.json'))) {
throw new Error('Cannot find package.json.')
}
const pkg = require(resolve(context, 'package.json'))
Object.assign(pkg, this.overrides)
writeFileSync(resolve(output, 'package.json'), JSON.stringify(pkg, null, 2))
mark('PackageJsonPlugin::onFinish(finish)')
done()
}
}

export function usePackageJsonPlugin(overrides: Overrides): PackageJsonPlugin {
return new PackageJsonPlugin(overrides)
}

0 comments on commit 69789db

Please sign in to comment.