Skip to content

Instantly share code, notes, and snippets.

@mattlubner
Created January 28, 2020 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattlubner/4a3eff31455180e8dac8ad8cf1b17ed1 to your computer and use it in GitHub Desktop.
Save mattlubner/4a3eff31455180e8dac8ad8cf1b17ed1 to your computer and use it in GitHub Desktop.
Razzle plugin to force certain environment variables to be resolved dynamically at runtime for the nodejs bundle
import _ from 'lodash';
/**
* The passed list of environment variables will be removed from the nodejs
* instance of webpack.DefinePlugin, so they can be resolved dynamically at
* runtime.
* @example
* // Include this in the plugins array exported by razzle.config.js
* const nodeRuntimeVarsPlugin = createRazzlePluginNodeRuntimeVars('PORT', 'HOST');
* @param {String} ...nodeRuntimeVars
* @return {Function}
*/
const createRazzlePluginNodeRuntimeVars = (...nodeRuntimeVars) => (
config,
{ target, dev },
webpack,
) => {
if (target !== 'node') {
// Don't change dotenv build-time behavior for the client bundle
return config;
}
const definePluginIndex = config.plugins.findIndex(
plugin => plugin instanceof webpack.DefinePlugin && plugin.definitions,
);
if (typeof definePluginIndex !== 'undefined') {
const nodeRunetimeVarsBlacklist = nodeRuntimeVars.map(
name => `process.env.${name}`,
);
const filteredDefinitions = _.omitBy(
config.plugins[definePluginIndex].definitions,
(value, key) => nodeRunetimeVarsBlacklist.includes(key),
);
config.plugins[definePluginIndex] = new webpack.DefinePlugin(
filteredDefinitions,
);
}
return config;
};
export default createRazzlePluginNodeRuntimeVars;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment