Created
November 7, 2020 11:09
-
-
Save VanTanev/203a16a1752900b4c007513f9d33b594 to your computer and use it in GitHub Desktop.
Enable CRA-like environment variable passing in preact-cli
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 webpack from 'webpack' | |
export default { | |
/** | |
* Function that mutates the original webpack config. | |
* Supports asynchronous changes when a promise is returned (or it's an async function). | |
* | |
* @param {object} config - original webpack config. | |
* @param {object} env - options passed to the CLI. | |
* @param {WebpackConfigHelpers} helpers - object with useful helpers for working with the webpack config. | |
* @param {object} options - this is mainly relevant for plugins (will always be empty in the config), default to an empty object | |
**/ | |
webpack(config, env, _helpers, _options) { | |
config.resolve.alias['react'] = 'preact/compat' | |
config.resolve.alias['react-dom'] = 'preact/compat' | |
config.resolve.alias['@types/react'] = 'preact/compat' | |
config.resolve.alias['@types/react-dom'] = 'preact/compat' | |
config.plugins.push(new webpack.DefinePlugin(getClientEnvironment().stringified)) | |
}, | |
} | |
// Get client environment, ala CRA. Use the same `REACT_APP_` prefix | |
// based on https://github.com/facebook/create-react-app/blob/5bd6e73047ef0ccd2f31616255c79a939d6402c4/packages/react-scripts/config/env.js | |
const REACT_APP = /^REACT_APP_/i | |
function getClientEnvironment() { | |
const raw = Object.keys(process.env) | |
.filter((key) => REACT_APP.test(key)) | |
.reduce((env, key) => { | |
env[key] = process.env[key] | |
return env | |
}, {}) | |
const stringified = { | |
'process.env': Object.keys(raw).reduce((env, key) => { | |
env[key] = JSON.stringify(raw[key]) | |
return env | |
}, {}), | |
} | |
return { stringified } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment