I'm using Vue 3 and Webpack 5 and wanted to install dotenv-webpack, but I can't get it to work.
Here's full code: https://github.com/golebiewska-n/webpack5-vue3
Setup: package.json script I'm using to launch the app
webpack-cli serve
webpack.config.js:
const Dotenv = require('dotenv-webpack')
...
module.exports = (env) => {
return {
...
plugins: [
...
new Dotenv()
]
}
}
.env (added in the root folder of my app)
VUE_APP_VAR=123
main.js:
console.log(process.env)
and output in console is:
MISSING_ENV_VAR
I tried removing new webpack.DefinePlugin({...}) from plugins in webpack config, but it didn't help.
In fact you successfully loaded the
.envfile withdotenv-webpackand theVUE_APP_VARis accessible. It is just you cannot use the entireprocess.envobject asdotenv-webpackdoes not allow it showing youMISSING_ENV_VARinstead.If you chnange line 12 in your
src\Layout.vueas follows:you get your
123value of the variable in your Vue app.The reason is at the time of building your application with webpack
dotenv-webpackreplaces the explicit stringprocess.env.SOME_EXPLICIT_VARIABLE_NAME_HEREexisting in your code with the actual value ofSOME_EXPLICIT_VARIABLE_NAME_HEREif that exist in the Webpack JS environment's actualprocess.envobject.This means you never get the entire
process.envobject accessible in your webpack bundle, and the bundle does not comprise the variable names likeVUE_APP_VAR=123. This is the goal ofdotenv-webpack.You can get some more details in my answer here.
PS:
DefinePlugin, being returned in the build config, could overrideprocess.env. It does so in Vue CLI (which is hardly justifiable). So its effect there sould be neutralized manually fordotenv-webpackto work within Vue CLI (v4 and v5) applications as expected.