Search code examples
node.jsreactjsnpmreact-reduxcreate-react-app

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


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/.


Solution

  • From your edit I would suggest to try:

    import packageJson from '/package.json';
    

    You could also try to create a symlink:

    # From the project root.
    cd src; ln -s ../package.json package.alias.json
    

    List contents of src directory and you'll see the symlink.

    ls
    #=> package.alias.json -> ../package.json
    

    Adding the .alias helps reduce the "magic" for others and your future self when looking at this. Plus, it'll help text editors keep them apart. You'll thank me later. Just make sure you update your JS code to import from ./package.alias.json instead of ./package.json.

    Also, please take a look at this question: The create-react-app imports restriction outside of src directory