Node / NPM:如何使用.sh文件调用传递参数

时间:2021-03-15 23:18:58

I am using package.json's script block to call postinstall.sh script immediately after yarn install and yarn install --production.

我正在使用package.json的脚本块在纱线安装和纱线安装 - 生产后立即调用postinstall.sh脚本。

postinstall.sh contains some private npm packages, so we want to download devDependencies of those packages only when the environment is development and we want to ignore when the environment is production.

postinstall.sh包含一些私有的npm包,所以我们只想在环​​境开发时下载这些包的devDependencies,并且我们想在环境生产时忽略它们。

package.json

的package.json

  "private": true,
  "scripts": {
    "postinstall": "./postinstall.sh"
  }

postinstall.sh

postinstall.sh

 # Get the input from user to check server is Production or not
echo
echo "INFO: We are not downloading Development dependencies of following services in Production environment:
echo "WARN: please enter 'yes' or 'no' only."

while [[ "$PRODUCTION_ENV" != "yes" && "$PRODUCTION_ENV" != "no" ]]
do
  read -p "Is this Production environment?(yes/no): " PRODUCTION_ENV
done

if [[ "$PRODUCTION_ENV" == "yes" ]]; then
   ENV='--only=production'
fi

npm install $ENV --ignore-scripts pkg-name

The problem with above script is we don't want any user interaction, so how can I pass an argument from package.json depending on the environment?

上面脚本的问题是我们不希望任何用户交互,所以如何根据环境从package.json传递参数?

2 个解决方案

#1


0  

in package.json you should be able to check NODE_ENV and then only execute your bash script when it's not production:

在package.json中,您应该能够检查NODE_ENV,然后只在不生成时执行您的bash脚本:

  "private": true,
  "scripts": {
    "postinstall": "[ \"$NODE_ENV\" != production ] && ./postinstall.sh"
  }

This should work because on a production environment you would install your modules with npm install --production so the script will not run.

这应该有效,因为在生产环境中,您将使用npm install --production安装模块,因此脚本将无法运行。

#2


0  

And, simple answer to this is "postinstall": "./postinstall.sh \"$NODE_ENV\"". So, final look a like below.

而且,简单的回答是“postinstall”:“。/ posttinstall.sh \”$ NODE_ENV \“”。所以,最终看起来像下面。

"private": true,
"scripts": {
   "postinstall": "./postinstall.sh \"$NODE_ENV\""
}

#1


0  

in package.json you should be able to check NODE_ENV and then only execute your bash script when it's not production:

在package.json中,您应该能够检查NODE_ENV,然后只在不生成时执行您的bash脚本:

  "private": true,
  "scripts": {
    "postinstall": "[ \"$NODE_ENV\" != production ] && ./postinstall.sh"
  }

This should work because on a production environment you would install your modules with npm install --production so the script will not run.

这应该有效,因为在生产环境中,您将使用npm install --production安装模块,因此脚本将无法运行。

#2


0  

And, simple answer to this is "postinstall": "./postinstall.sh \"$NODE_ENV\"". So, final look a like below.

而且,简单的回答是“postinstall”:“。/ posttinstall.sh \”$ NODE_ENV \“”。所以,最终看起来像下面。

"private": true,
"scripts": {
   "postinstall": "./postinstall.sh \"$NODE_ENV\""
}