1

I have an SPA application (in React) built with Webpack (as part of create-react-app) where I display a version number retrieved from the package.json likes this:

import npmInfo from 'package.json' ... <div className="version">{npmInfo.version}</div> 

However this results in also other package.json being part of built javascript file and exposed to the public.

Is there an approach to retrieve just the version from package.json other than reading it in parent the process and setting it to environment variable (and reading it via process.env.VERSION) ?

4
  • Will that actually end up in the built result? I'd imagine unused info will be tree-shaken or otherwise optimised out. Commented Jul 31, 2017 at 7:53
  • Try `import { version } from 'package.json', does that work? Commented Jul 31, 2017 at 7:55
  • @casraf No, it still adds the whole package.json Commented Jul 31, 2017 at 14:10
  • @jonrsharpe It is there as a JSON Commented Jul 31, 2017 at 14:10

1 Answer 1

1

I'm not sure if this will solve your problem, as you are a bit against using (or rather setting?) environment variables, but if your application is ran or compiled by a npm script, you could use process.env.npm_package_version.

Note: this will only be available if you use npm scripts.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for pointing me in the right direction but this method unfortunately does not work with create-react-app. But I was inspired by it and ended up with cross-env REACT_APP_VERSION=$npm_package_version react-scripts start script.
Great! It'd be cool if you could write an answer about it, so others will be able to notice the solution.
I intend to but I am not that happy with the aforementioned solution. When I have more time I will try to find out more about this and post the best solution I could come with.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.