使用sh-ac指定package.json脚本以指向特定.env(react)时,权限被拒绝



我刚刚使用npx create react app创建了一个新的react app,并添加了一些.env文件(.env.staging、.env.development、.env.production(我不想使用像envcmd这样的依赖项,我看到了一些关于使用shell cmd来指定我想要的.env文件的帖子。

package.json文件脚本如下:

"scripts": {
"build": "sh -ac '. ./.env.${REACT_APP_ENV}; react-scripts build'",
"build:staging": "REACT_APP_ENV=staging npm run build",
"build:production": "REACT_APP_ENV=production npm run build"
},

.env.staging:

REACT_APP_CUSTOM_NODE_ENV = "staging"
REACT_APP_API_ENDPOINT = "https://boarding.staging.com"
REACT_APP_API_ENDPOINT_TITLE = "Staging Env"

当执行>npm run build:staging时,我得到以下错误

>npm run build:staging

> env-vars@0.1.0 start:staging
> REACT_APP_ENV=staging npm run start
> env-vars@0.1.0 start
> sh -ac './ .env.${REACT_APP_ENV}; react-scripts start'
sh: 1: ./: Permission denied

该应用程序仍在运行,但我无法为我的变量指定所需的.env.staging文件。在cmd行中运行sh-ac,但仍然出现相同的错误。

✘ ~/env-vars >chmod +u+r+w+x ./.env.staging
✘ ~/env-vars >ls -la .env.staging
-rwxr-xr-x 1 john john 132 Jan 19 20:38 .env.staging
✘ ~/env-vars > sh -ac './ .env.staging';
sh: 1: ./: Permission denied

我不想为每个文件设置权限,因为这似乎是错误的,但如果我尝试它,我仍然会得到同样的错误。你觉得我做错了什么吗?

甚至尝试过bash"staging": "bash -ac ./ ./.env.staging; react-scripts start"

npm run staging
> playground@0.1.0 staging
> bash -ac ./ ./.env.staging; react-scripts start
./.env.staging: ./: Is a directory

和复制脚本从其他文章我得到找不到!

"start-env": "sh -ac '. /home/geuxor/code/playground/playground/.env.${REACT_APP_ENV}; react-scripts start'",
"start-dev": "REACT_APP_ENV=staging npm run start-env",

npm run start-dev

> playground@0.1.0 start-dev
> REACT_APP_ENV=staging npm run start-env
> playground@0.1.0 start-env
> sh -ac '. /home/geuxor/code/playground/playground/.env.${REACT_APP_ENV}; react-scripts start'
sh: 1: /home/geuxor/code/playground/playground/.env.staging: REACT_APP_CUSTOM_NODE_ENV: not found
sh: 2: /home/geuxor/code/playground/playground/.env.staging: REACT_APP_API_ENDPOINT: not found
sh: 3: /home/geuxor/code/playground/playground/.env.staging: REACT_APP_API_ENDPOINT_TITLE: not found
  • 使用WSL2/Rect 17.0.2/尚未在React/zsh 4.8中安装dotenv作为其内置

Docker可以工作,因为您可以很容易地指定env-var,但在您的用例中引入它可能没有意义。为了解决你的问题,你必须牢记以下几点:默认情况下,标准shell不理解"dotenv"语法,导出env-vars的常见语法是这样的,因此您必须更新.env内容,使其看起来像这样:export VAR1=valueexport VAR2=valueNPM脚本已经在shell中运行,所以不需要用sh-ac"…"包装命令如果你仔细观察,你显示的package.json中的命令与正在执行的命令不同,我怀疑你可能错别字了?您收到的错误是因为您正在尝试执行当前目录(./(,但该目录将不起作用试试这个:

"build": "source ./.env.${REACT_APP_ENV} && react-scripts build",
"build:staging": "REACT_APP_ENV=staging npm run build",
"build:production": "REACT_APP_ENV=production npm run build",

使用source而不是。将减少打字错误的可能性&将确保在源变量因某种原因失败时不会发生构建。

最新更新