點燈坊

失くすものさえない今が強くなるチャンスよ

讀取 Package.json 的 Property

Sam Xiao's Avatar 2021-10-24

NPM Script 是很好用的工具,可自行將需要自動化部分整理成 NPM Script,由於 package.json 本身就是 JSON 格式,因此 NPM Script 也可以讀取到其 Property 加以應用。

Version

Node 14.18.1

Package.json

{
  "name": "apollo-mysql",
  "version": "1.0.0",
  "main": "src/index.js",
  "license": "MIT",
  "scripts": {
    "serve": "nodemon",
    "start": "node ./dist/index.js",
    "dev": "babel-node ./src/index.js",
    "prod": "yarn clean && cross-env NODE_ENV=production yarn build && yarn start",
    "clean": "rimraf dist",
    "build": "babel ./src --out-dir dist",
    "docker:build": "yarn clean && cross-env NODE_ENV=production yarn build && docker build -t $npm_package_name:$npm_package_version .",
    "docker:up": "docker-compose up -d",
    "docker:down": "docker-compose down",
    "mysql:up": "cd mysql && docker-compose up -d",
    "mysql:down": "cd mysql && docker-compose down"
  },
  "dependencies": {
    "apollo-server": "^2.9.7",
    "graphql": "^14.5.8",
    "knex": "^0.20.3",
    "mysql": "^2.17.1"
  },
  "devDependencies": {
    "@babel/cli": "^7.6.4",
    "@babel/core": "^7.6.4",
    "@babel/node": "^7.6.3",
    "@babel/preset-env": "^7.6.3",
    "cross-env": "^6.0.3",
    "nodemon": "^1.19.4",
    "rimraf": "^3.0.0"
  }
}

這是一個典型重度使用 NPM Script 的例子,可命令 Babel 轉譯、建置 Docker image 與啟動 MySQL … 等。

13 行

"docker:build": "yarn clean && cross-env NODE_ENV=production yarn build && docker build -t $npm_package_name:$npm_package_version .",

部署 Docker image 時版本非常重要,因此我們希望每次 build 時能自動讀取 package.jsonnameversion,此時我們可使用 $npm_package_ 接 property 名稱讀取。

Conclusion

  • 由於很多資訊已經在 package.json 內,實務上原本需要 Bash script 自動化的工作,其實都可改透過 NPM script 加以整合