,

Reusable Variables in package.json file of Angular project

Ever faced a requirement to have a variable like a feature in the package.json file of Angular or any node-based project? In this quick tutorial, you will get to know, how to define a variable in a package.json file that can be re-used at multiple places as we create in a Javascript file. Sometimes, you…

By.

min read

Ever faced a requirement to have a variable like a feature in the package.json file of Angular or any node-based project? In this quick tutorial, you will get to know, how to define a variable in a package.json file that can be re-used at multiple places as we create in a Javascript file.

Sometimes, you may have long scripts or file paths that need to be used again and again at multiple places spacially on scripts. In such a situation it is always prefered to use a common variable to make changes and maintenance very easy.

How to create a re-usable variable in the package.json file of the node application?

This is how you can make variables by defining the config property inside the pacakge.json file.

Create variables

Open the package.json file application root. Then add the "config" property as shown below:

{
  "name": "some-angular-application",
  "version": "0.0.0",
  "config": {},
  "scripts": {
   .....

....

A ‘config’ hash can be used to set configuration parameters used in package scripts that persist across upgrades.

 

Inside the “config” you can create multiple properties and assign any type of value even objects.

For example:

...

  "config": {
    "myAssetsFilePath":"./apps/deepFile/finance/pdfs/files",
    "isSecured":"--ssl true",
    "openOnServe":"--open"
  },

...

 

Using Config Values

Let’s have a look, at how we can utilize the defined values inside config.

Wherever you want to use the value, it will be used like

%npm_package_config_openOnServe%

Check the “start” script, and how we added the openOnServe value:

{
  "name": "some-angular-application",
  "version": "0.0.0",
  "config": {
    "myAssetsFilePath":"./apps/deepFile/finance/pdfs/files",
    "isSecured":"--ssl true",
    "openOnServe":"--open"
  },
  "scripts": {
    "ng": "ng",
    "start": "ng serve %npm_package_config_openOnServe%",
   ...
  },

Similarly, if you want to serve with HTTPS under a secured link:

...

"start": "ng serve %npm_package_config_openOnServe%  %npm_package_config_isSecured% ",

...

Leave a Reply

Your email address will not be published. Required fields are marked *