Forum Discussion

Krugerro's avatar
Krugerro
Copper Contributor
Mar 12, 2024

Access to proccess.env<variable> in spfx

My general aim is to use process.env<variableName> during build locally during development and in devops pipleines during deployment to inject some secrets and passwords. My story about this is pretty https://stackoverflow.com/questions/77018737/environment-variables-in-a-react-sharepoint-webpart (i'm not the author) so I tried every link touching this subject.

What I learned is:
in gulpfile none of plugins https://digitalworkplace365.wordpress.com/2020/03/05/using-env-files-in-sharepoint-framework-development/ is truthy in condition plugin instanceof webpack.DefinePlugin thus new instance of DefinePlugin is pushed which yields to error:

 

 

[08:22:42] Error - [webpack] TypeError: Cannot read properties of undefined (reading 'get')
[08:22:42] Error - 'webpack' sub task errored after 136 ms
Cannot read properties of undefined (reading 'get')
[08:22:42] 'bundle' errored after 9.47 s

 

When I manually change plugins array adding in gulpfile (code is simplified)

 

 let pluginDefine = cfg?.plugins?.[1];

    const currentEnv = getClientEnvironment().stringified;
      pluginDefine.definitions = {
        ...pluginDefine.definitions,
        ...currentEnv,
      };

 


where getClientEnvironment().stringified is:

SPFX_COMPUTER_VISION_ENDPOINT: '"SPFX_COMPUTER_VISION_ENDPOINT"',
SPFX_COMPUTER_VISION_KEY: '"SPFX_COMPUTER_VISION_KEY"'

 

My console.log(process.env.SPFX_COMPUTER_VISION_KEY) is undefined in any tsx file.

 

The only variable defined in DefinePlugin I can access is DEBUG.

I even started to edit node_modules@microsoft\spfx-heft-plugins\lib\plugins\webpackConfigurationPlugin\WebpackConfigurationGenerator.js where in DefinPlugin argument I added my variables which still gives undefined.

 

How can I inject my variables to process.env and use them during build?

Additional environment details

  • browser version: Version 122.0.2365.80 (Official build) (64-bit)
  • SPFx version: 1.17.4
  • Node.js version: 16.18.1
  • React version: 17.0.1
  • TypeScript version: 4.5.5
No RepliesBe the first to reply

Resources