This article will show you how to quickly access Nodejs variables from package.json, for example the version of your App.
There is two methods to achieve that.
This method is the quick and dirty way for achieving that. Simply do in your React or Vuejs app (or any other webapp) :
import packageJson from '/package.json' console.log(packageJson.version)
This one is pretty simple but you need to import the packageJson everywhere in the app and you expose all your package.json
file.
This method aim at declaring the variables you need in the .env
file to avoid exposing all your package.json
in your code deployed on server.
For that, just create an .env
file in your webapp (Vuejs, React, Angular, etc) :
touch .env
Open it with your editor and add :
For React app :
REACT_APP_VERSION=$npm_package_version REACT_APP_NAME=$npm_package_name
For Vue app :
VUE_APP_VERSION=$npm_package_version VUE_APP_NAME=$npm_package_name
Then in any file of your webapp simply use :
console.log(`${process.env.REACT_APP_NAME} ${process.env.REACT_APP_VERSION}`)
This will allow you to access package.json
variables anywhere in your app without having to expose all your package.json
file.
All variables accessibles in NodeJS are listed here
Variables you add in .env are not directly accessible. Don’t forget to restart your server of webapp (Vuejs, React, Angular) after adding new one !