-
-
Save Kevinwkd/319d0c81413d18915f1b01bb33882313 to your computer and use it in GitHub Desktop.
This file contains 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
const webpack = require('webpack'); | |
const dotenv = require('dotenv'); | |
const fs = require('fs'); // to check if the file exists | |
const path = require('path'); // to get the current path | |
module.exports = (env) => { | |
// Get the root path (assuming your webpack config is in the root of your project!) | |
const currentPath = path.join(__dirname); | |
// Create the fallback path (the production .env) | |
const basePath = currentPath + '/.env'; | |
// We're concatenating the environment name to our filename to specify the correct env file! | |
const envPath = basePath + '.' + env.ENVIRONMENT; | |
// Check if the file exists, otherwise fall back to the production .env | |
const finalPath = fs.existsSync(envPath) ? envPath : basePath; | |
// Set the path parameter in the dotenv config | |
const fileEnv = dotenv.config({ path: finalPath }).parsed; | |
// reduce it to a nice object, the same as before (but with the variables from the file) | |
const envKeys = Object.keys(fileEnv).reduce((prev, next) => { | |
prev[`process.env.${next}`] = JSON.stringify(fileEnv[next]); | |
return prev; | |
}, {}); | |
return { | |
plugins: [ | |
new webpack.DefinePlugin(envKeys) | |
] | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment