Search code examples
reactjsbuildenvironment-variablescreate-react-appnetlify

Unable to use $npm_package_version when deploying to Netflify


I have a create-react-app (CRA) deployed to Netlify and I copied over my .env file contents over to Netlify's environment variables build settings. I added REACT_APP_VERSION as the key with $npm_package_version as the value.

But when the app got deployed, this particular environment variable is being shown as a literal string. It doesn't get evaluated to 0.1.0 as what is defined on my package.json file. All my other environment variables work just fine because they are string literals. How do I fix this?


Solution

  • I was able to fix this by injecting environment variables using local build plugins.

    Here's my file structure:

    > project
      > plugins
        > netlify
          > env
            - index.js
            - manifest.yml
            - package.json ---> only for the plugin (to define as a module)
      ...
      - netlify.toml
      - package.json       ---> where I need to grab values from
      ...
    

    And these are the contents of the files:

    index.js

    export const onPreBuild = function ({ netlifyConfig, packageJson }) {
        netlifyConfig.build.environment.REACT_APP_NAME = packageJson.name;
        netlifyConfig.build.environment.REACT_APP_VERSION = packageJson.version;
    };
    

    manifest.yml

    name: netlify-env
    

    package.json (inside of plugins/netlify/env directory)

    {
        "name": "netlify-env",
        "version": "1.0.0",
        "type": "module"
    }
    

    netlify.toml

    [[plugins]]
    package = "/plugins/netlify/env"