Search code examples
create-react-apppackage.json

How to access the dependency versions in a Create-React-App


In a create-react-app i would like to access some properties of the package.json and show those to the user in the browser. Like the version of the app and the version of some of the dependencies specified in the package.json.

How would I access those properties, without importing and exposing the whole package.json to the client?


Solution

  • Executing npm run build on the create-react-app provides a production bundle in the ./build directory.

    Solution 1: The way it works it does not expose the rest of the package.json content to the production bundle when making a destructured import. (E.g. previous answer from Devchris)

    import { dependencies } from './package.json';
    

    Solution 2: By extending the npm scripts it is possible to read and expose the package.json into the node environment and read it from there at build time (https://create-react-app.dev/docs/adding-custom-environment-variables)

    process.env.REACT_APP_DEPENDENCIES
    

    Note: The variable must start with 'REACT_APP_'