读取JSON并分配给make变量列表



我可以通过以下方式从package.json中获取值:

LAST_VERSION := $(shell node -p "require('./package.json').version")

但是如果我需要几个值呢?类似:

PROJECT     := $(shell node -p "require('./package.json').name")
LAST_VERSION:= $(shell node -p "require('./package.json').version")
DESCRIPTION := $(shell node -p "require('./package.json').description")
PROJECT_URL := $(shell node -p "require('./package.json').repository.url")

这是唯一的路吗?也许有一种方法可以创建一个列表。

最后,我想到了这个:

define GetFromPkg
$(shell node -p "require('./package.json').$(1)")
endef
PROJECT      := $(call GetFromPkg,name)
LAST_VERSION := $(call GetFromPkg,version)
DESCRIPTION  := $(call GetFromPkg,description)
PROJECT_URL  := $(call GetFromPkg,repository.url)

以下是已接受答案的调整版本。

通过使用类似data.profile.name的参数调用GetValueFromJson,可以轻松地获取嵌套值。

define GetValueFromJson
$(shell node -p '
    const getVal = (key = "", obj = {}) => {
          const currKey = key.split(".")[0];
          const val = obj[currKey];
          if(typeof val !== "object") return val;
          const nextKey = key.split(".").slice(1).join(".");
          return getVal(nextKey, val);
    }; 
    getVal(`$(1)`.replace(" ", ""), require("./package.json")); 
')
endef
PORT := $(call GetValueFromJson, config.port)
# make run
run:
    PORT=${PORT} node server.js

最新更新