简体   繁体   English

是否可以在 npm 脚本中使用 .env 包中的环境变量

[英]Is it possible to use environment variables from .env package in the npm scripts

I have dotenv installed in my cypress project and variables in .env file, which looks like this:我在赛普拉斯项目中安装了 dotenv,在 .env 文件中安装了变量,如下所示:

USER=Admin 

Is there a way for me to use my env variable USER inside of the npm scripts?有没有办法让我在 npm 脚本中使用我的环境变量USER

  "scripts": {
    "cypress:open": "npx cypress open --env grepTags=USER"
  },

I did a bit of searching and found this related StackOverflow thread that may help you: How to use environment variables in package.json我做了一些搜索,发现这个相关的 StackOverflow 线程可能会对您有所帮助: How to use environment variables in package.json

I believe it should be possible to parse the JSON with the fs module, traverse the JavaScript object, insert your env variable in a separate script, and write to the file system the same package.json but with the env variable included.我相信应该可以使用 fs 模块解析 JSON,遍历 JavaScript 对象,将您的 env 变量插入到单独的脚本中,并将相同的 package.json 但包含 env 变量写入文件系统。 This may be a poor solution though because it will probably need to be run following every change to the contents of the .env file ...这可能是一个糟糕的解决方案,因为它可能需要在每次更改 .env 文件的内容后运行......

 const fs = require("fs"); require("dotenv").config(); const myVar = process.env.MY_ENV_VAR; let rawJson = fs.readFileSync("package.json"); let parsed = JSON.parse(rawJson); parsed.scripts.start = myVar; // or whatever string defines your script let backToJson = JSON.stringify(parsed); fs.writeFileSync("package.json", backToJson);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM