Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fivethreeo/a1717cef2363783d73b6dd018b621a11 to your computer and use it in GitHub Desktop.
Save fivethreeo/a1717cef2363783d73b6dd018b621a11 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
/**
* 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 = config.plugins[definePluginIndex].definitions.entries().reduce((result, entry)=>{
if (!nodeRunetimeVarsBlacklist.includes(entry[0])) {
result[entry[0]] = entry[1];
}
}, {});
config.plugins[definePluginIndex] = new webpack.DefinePlugin(
filteredDefinitions,
);
}
return config;
};
export default createRazzlePluginNodeRuntimeVars;
'use strict';
const createRazzlePluginNodeRuntimeVars = require('razzle-plugin-node-runtime-vars.js');
module.exports = {
plugins: [createRazzlePluginNodeRuntimeVars('PORT', 'HOST')],
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment