HomeContact
NodeJS
Access package.json of Nodejs variables inside a Webapp.
January 26, 2021
1 min

Table Of Contents

01
Directly import the package.json file
02
Declare the variables you need as a global env variables

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.

Directly import the package.json file

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.

Declare the variables you need as a global env variables

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 !


Tags

javascriptnodejs

Related Posts

How to call a route internally using NodeJS
April 11, 2022
1 min
© 2023, All Rights Reserved.

Quick Links

Contact Us

Social Media