概要
npm workspaceを利用するとき、package.jsonの初期値を設定することで構築の手間を減らす方法を示す。
これによりnpm initしたときに、npm scriptsやnpmパッケージが初期設定される。
環境
% node -v v16.13.2 % npm -v 8.10.0
実装
% tree -a -I '.git|.gitignore' . ├── .npm-init.js ├── .npmrc └── package.json
package.json
{ "name": "hoge", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "workspaces": [], "dependencies": { "yargs": "17.5.1" } }
.npm-init.js
const yargs = require("yargs/yargs"); const { hideBin } = require("yargs/helpers"); const argv = yargs(hideBin(process.argv)).argv; const scope = "@tom-256"; module.exports = { name: `${scope}/${argv.w}`, version: "0.0.0", description: "", main: "dist/index.js", scripts: { test: "jest", build: "tsc", }, keywords: [], author: "", license: "ISC", dependencies: { express: "4.18.1", }, devDependencies: { jest: "28.1.0", }, };
.npmrc
init-module=.npm-init.js
この状態でワークスペースを作ると下記のようになる。
npm init -y -w package-a Wrote to /Users/.../hoge/package-a/package.json: { "name": "@tom-256/package-a", "version": "0.0.0", "description": "", "main": "dist/index.js", "scripts": { "test": "jest", "build": "tsc" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "4.18.1" }, "devDependencies": { "jest": "28.1.0" } }
まとめ
npm init時のscriptsやnpmパッケージの初期値を設定する方法を示した。
ただしこのままだと、初期値のnpmパッケージのバージョンが古くなってしまう。
npmパッケージのバージョン管理はRenovate等でおこなうことを想定したときに、.npm-init.jsに記述してあるバージョンをどのように管理にするか考える必要がある。
また、tscofnig.jsonや.eslinrc.jsなどの設定ファイルも構築するように.npm-init.jsに記述しておくことで更に手間を減らし、設定を統一することができる。
モノレポで構築の手間を減らしたり、設定を統一するケースで有用なのでメモした。
参考情報
https://docs.npmjs.com/cli/v8/commands/npm-init
https://docs.npmjs.com/cli/v8/using-npm/config#init-module
https://docs.npmjs.com/creating-a-package-json-file
補足
npm scriptsの設定を揃えたい場合はnpm set scriptを利用する。
https://docs.npmjs.com/cli/v8/commands/npm-set-script
例:npm set-script test "jest" -ws