Last active
July 4, 2023 05:20
-
-
Save brunos3d/933187d4e3e093383df6c5fae5bccff4 to your computer and use it in GitHub Desktop.
Webpack load env-file using Dotenv Plugin using Nx pattern (webpack.config.js)
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
const { composePlugins, withNx } = require('@nx/webpack'); | |
const Dotenv = require('dotenv-webpack'); | |
const fs = require('fs'); | |
const path = require('path'); | |
// check for available env file using Nx conventions and return the path | |
function resolveEnvFile(basePath = __dirname) { | |
const envFiles = [ | |
`.env.${process.env.NX_TASK_TARGET_CONFIGURATION}.${process.env.NX_TASK_TARGET_TARGET}`, | |
`.${process.env.NX_TASK_TARGET_CONFIGURATION}.${process.env.NX_TASK_TARGET_TARGET}.env`, | |
`.env.${process.env.NX_TASK_TARGET_TARGET}`, | |
`.${process.env.NX_TASK_TARGET_TARGET}.env`, | |
`.env.${process.env.NX_TASK_TARGET_CONFIGURATION}`, | |
`.${process.env.NX_TASK_TARGET_CONFIGURATION}.env`, | |
`.local.env`, | |
`.env.local`, | |
`.env`, | |
]; | |
for (const file of envFiles) { | |
const envPath = path.resolve(basePath, file); | |
if (fs.existsSync(envPath)) { | |
return envPath; | |
} | |
} | |
return null; | |
} | |
// Nx plugins for webpack. | |
module.exports = composePlugins(withNx(), (config) => { | |
// Update the webpack config as needed here. | |
// e.g. `config.plugins.push(new MyPlugin())` | |
config.plugins.push( | |
new Dotenv({ | |
path: resolveEnvFile(), | |
}) | |
); | |
return config; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment