Warning
I have stopped maintaining this project.
I started using vite and because of that haven't used webpack in a while. I do not think I will be moving back to webpack.
I am archiving this project for now. I will delete it at the end of 2023. Please save yourself a copy.
Use envjoi
to read, validate and use environment variables from an .env
file when building with webpack and in your finished build as well!
// webpack.config.ts
import { envjoi } from 'envjoi'
const envSchema = Joi.object({
PORT: Joi.number().greater(0).default(8080),
PUBLIC_PATH: Joi.string().required(),
})
const envjoiPlugin = envjoi(envSchema)
const configuration: webpack.Configuration = {
output: {
// Use all environment variables including
// those from .env in your webpack config
publicPath: process.env.PUBLIC_PATH,
},
plugins: [
// Only expose environment variables
// validated against your Joi schema in
// your builds.
envjoiPlugin,
],
...
You can access a single environment variable ...
const FOO = process.env.FOO
No. We use webpack's DefinePlugin
to replace occurrences of process.env.FOO
in your code with the value of FOO
as defined in your .env
file. To support something like
const env = process.env
or
const { FOO, BAR, BAZ } = process.env
we would need to replace all occurrences of process.env
with everything you put in your .env
, including secrets you do not want in your finished builds. To protect you from accidentally exposing your secrets, envjoi
does not support destructuring.
npm install --save-dev @twiddler/envjoi
function envjoi(schema: Joi.ObjectSchema, path?: string): DefinePlugin
:
schema
of your environment variables defined withJoi
path
to your.env
file (default to./.env
)- returns an instance of
webpack.DefinePlugin
Pull requests are always welcome! :)