Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.