简体   繁体   English

在 react 组件文件中使用 package.json 文件好不好?

[英]Is it good to use package.json file in react component file?

I have to use version mentioned in package.json file in front-end(react js) file.我必须在前端(react js)文件中使用 package.json 文件中提到的版本。

{
  "name": "asdfg",
  "version": "3.5.2", // want to use this
  "description": "description",
  "scripts": {}
  //etc etc etc
  ......
}

Send package.json [version] to Angularjs Front end for display purposes 将 package.json [version] 发送到 Angularjs 前端用于显示

I'd gone through above post and found two ways for the same.我已经浏览了上面的帖子,并找到了两种相同的方法。 but none of them I was asked to implement.但我没有被要求实施。

#1. #1. During build process在构建过程中

#2. #2. By creating endpoint通过创建端点

So I want to know the approach below is valid/good or not ?所以我想知道下面的方法是否有效/好?

react-front-end-file.js react-front-end-file.js

import packageJson from '../package.json'; // imported
...
...
// Usage which gives me version - 3.5.2
<div className='app-version'>{packageJson.version}</div> 

Let me know if this approach is fine.让我知道这种方法是否合适。

The below 2 approaches seems to have either dependency or add an extra implentation which might not be needed以下 2 种方法似乎具有依赖性或添加了可能不需要的额外实现

  1. During build process - ( has dependency on module bundler like webpack etc.)在构建过程中 - (依赖于模块打包器,如 webpack 等)

  2. By creating endpoint - ( needs an extra code at server just to get version )通过创建端点 - (在服务器上需要额外的代码来获取版本)

Instead, As package.json is a file which takes json object in it so you can use it to import json and use its any keys mentioned in that file ( version in your case but only constraint here is, you should have access to package.json file after application deployment, so dont forget to move file in deployment environment )相反,由于 package.json 是一个包含 json 对象的文件,因此您可以使用它来导入 json 并使用该文件中提到的任何键(版本在您的情况下,但这里只有约束,您应该有权访问 package.json )。应用程序部署后的 json 文件,所以不要忘记在部署环境中移动文件)

So your approach seems to be fine.所以你的方法似乎没问题。

I would do something like this: In your module bundler, require your package json file and define a global variable and use it wherever you want我会做这样的事情:在你的模块捆绑器中,需要你的包 json 文件并定义一个全局变量并在任何你想要的地方使用它

eg I do something like this in webpack:例如我在 webpack 中做这样的事情:

const packageJson = require('./package.json')

const plugins = [
  new webpack.DefinePlugin(
    {
      '__APPVERSION__': JSON.stringify(packageJson.version)
    }
 )
]

React Component:反应组件:

<div className='app-version'>{__APPVERSION__}</div>

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

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