Get version number from package.json in React Redux (create-react-app)

Baldeep picture Baldeep · Aug 31, 2017 · Viewed 46k times · Source

OP EDIT: If anyone else comes across this: the app was created using create-react-app, which limits importing to within the src folder. However if you upgrade react-scripts to v1.0.11 it does let you access package.json.

I'm trying to get the version number from package.json in my app.

I've already tried these suggestions, but none of them have worked as I can't access package.json from outside the src folder (might be due to React, I'm new to this). Moving package.json into src then means I can't run npm install, npm version minor, and npm run build from my root folder. I've tried using process.env.npm_package_version but that results in undefined.

I'm using Jenkins, and I haven't set it up to push the commits up yet, but the only idea I have is to get the version from the tags in GitLab, but I have no idea how to do that, and it would add unnecessary dependency to the repo, so I would really like to find an alternative.

EDIT: My file structure is like:

--> RootAppFolder
    |--> build
    |--> node_modules
    |--> public
    |--> src
         |--> Components
              |--> Root.js
    |
    |--> package.json

So to access package.json from Root.js I have to do import packageJson from './../../package.json' and then I get the following error:

./src/components/Root.js

Module not found: You attempted to import ./../../package.json which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.

Answer

talves picture talves · Jun 12, 2018

Solving this without importing and exposing package.json to the create-react-app

Requires: version 1.1.0+ of create-react-app

.env

REACT_APP_VERSION=$npm_package_version
REACT_APP_NAME=$npm_package_name

index.js

console.log(`${process.env.REACT_APP_NAME} ${process.env.REACT_APP_VERSION}`)

Note: the version (and many other npm config params) can be accessed

Note 2: changes to the .env file will be picked only after you restart the development server