Configuration variables in SPFx
February 11, 2020
Thank you to Sergei Sergeev for the info.
A common problem that developers have is needing to have a set of values for testing locally that are different to those in production. For example, an API URL that targets a local server in development, and the live one in production. Being able to separate the values automatically depending on the current working environment can help speed up development without worrying about making any accidental/undesired changes to production data.
In SPFx we can use our gulpscript.js
and webpack to detect what environment we are in and inject different values accordingly.
Setup
For this method to work we need to install webpack-merge and cross-env to help merge our new webpack config and inject environment variables for run time.
_1yarn add webpack-merge cross-env
Once installed, we need to add a new command to our serve
script:
The new script uses cross-env to inject the NODE_ENV value for dev purposes. So when we start the debugging process, by running yarn serve
, the value will be set. In production, the value won't be changed and will run in production mode by default.
Config
We now need to change our gulpscript.js
to look for this flag at build time and inject the specific values we require.
In the below example we inject a single apiUrl
that is different between environments:
Accessing the variables
Now that we have our apiUrl
set, we need a way to access it in code. To do this we can set up a helper class that exposes the variables:
And then use in code: