Created
January 28, 2020 19:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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