Skip to content

Commit

Permalink
fix(rspack): ensure NX_PUBLIC env vars are available to applications #…
Browse files Browse the repository at this point in the history
…28720 (#28751)

<!-- Please make sure you have read the submission guidelines before
posting an PR -->
<!--
https://github.com/nrwl/nx/blob/master/CONTRIBUTING.md#-submitting-a-pr
-->

<!-- Please make sure that your commit message follows our format -->
<!-- Example: `fix(nx): must begin with lowercase` -->

<!-- If this is a particularly complex change or feature addition, you
can request a dedicated Nx release for this pull request branch. Mention
someone from the Nx team or the `@nrwl/nx-pipelines-reviewers` and they
will confirm if the PR warrants its own release for testing purposes,
and generate it for you if appropriate. -->

## Current Behavior
<!-- This is the behavior we have today -->
With Webpack, we setup DefinePlugin to define `NX_PUBLIC` env vars.
This was not replicated in Rspack


## Expected Behavior
<!-- This is the behavior we should expect with the changes in this PR
-->
Ensure `NX_PUBLIC` env vars are included in the DefinePlugin

## Related Issue(s)
<!-- Please link the issue being fixed so it gets closed when this is
merged. -->

Fixes #28720
  • Loading branch information
Coly010 authored Nov 1, 2024
1 parent 276e799 commit ab8d77e
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions packages/rspack/src/utils/with-web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,33 @@ export function withWeb(opts: WithWebOptions = {}) {
new rspack.EnvironmentPlugin({
NODE_ENV: isProd ? 'production' : 'development',
}),
new rspack.DefinePlugin(
getClientEnvironment(isProd ? 'production' : undefined).stringified
),
],
};
};
}

function getClientEnvironment(mode?: string) {
// Grab NODE_ENV and NX_PUBLIC_* environment variables and prepare them to be
// injected into the application via DefinePlugin in webpack configuration.
const nxPublicKeyRegex = /^NX_PUBLIC_/i;

const raw = Object.keys(process.env)
.filter((key) => nxPublicKeyRegex.test(key))
.reduce((env, key) => {
env[key] = process.env[key];
return env;
}, {});

// Stringify all values so we can feed into webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};

return { stringified };
}

0 comments on commit ab8d77e

Please sign in to comment.