简体   繁体   English

如何在包 json 或其他方式中使用 env 变量

[英]How to use env variables in package json or the other way around

I have just created my first React app but at the end I noticed that I am repeating myself in one place.我刚刚创建了我的第一个 React 应用程序,但最后我注意到我在一个地方重复了自己。 I needed to add the homepage field to package.json since I am hosting my app under a sub-directory.我需要将homepage字段添加到 package.json,因为我将我的应用程序托管在一个子目录下。 But then I also needed to add the same homepage as the basename for my router.但随后我还需要添加与路由器basename相同的主页。 Well, that means I could update one and forget to update the other, it's not DRY.嗯,这意味着我可以更新一个而忘记更新另一个,这不是 DRY。

Is there a way to have my homepage path only in one place?有没有办法让我的主页路径只在一个地方? Maybe use the .env variable in package.json?也许在 package.json 中使用 .env 变量?

my package.json (notice homepage)我的package.json (注意主页)

{
  "name": "react-app",
  "version": "0.1.0",
  "private": true,
  "homepage": "/react-app/build",  
  "dependencies": {
    ...
  },

and also in my .env file也在我的 .env 文件中

REACT_APP_HOMEPAGE=/react-app/build

Then in my router I needed to add this然后在我的路由器中我需要添加这个

<Router basename={process.env.REACT_APP_HOMEPAGE}>

Having my homepage path in 2 places is not a good idea.将我的主页路径放在 2 个地方并不是一个好主意。 Is there a way I can use my ENV variable in the package.json file or maybe use the package.json variable in my app?有没有办法可以在 package.json 文件中使用我的 ENV 变量,或者在我的应用程序中使用 package.json 变量?

As I already mentioned in the comment section.正如我在评论部分已经提到的。 Its not an ideal way of doing things but the below solution should work.它不是一种理想的做事方式,但以下解决方案应该有效。 You should instead define the homepage in your package.json as you did then in the component that uses the router, you can import the package.json and read the homepage property from it.您应该像在使用路由器的组件中那样在 package.json 中定义主页,您可以导入 package.json 并从中读取主页属性。 as in

    let packageJson = require('../path/to/package.json');
    packageJson.homepage

If you later inside the package.json needs to use that value, you can then do something like如果您稍后在 package.json 中需要使用该值,则可以执行以下操作

$npm_package_homepage.

you can find more details about using variables in package.json here Referencing variables in package.json This way when there is a need for editing you can do it in one place inside the package.json and all the other places will take effect.您可以在此处找到有关在 package.json 中使用变量的更多详细信息在 package.json 中引用变量这样,当需要编辑时,您可以在 package.json 中的一个地方进行编辑,所有其他地方都会生效。

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

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