Reputation: 23
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.
Upvotes: 1
Views: 700
Reputation: 7858
In fact you successfully loaded the .env
file with dotenv-webpack
and the VUE_APP_VAR
is accessible. It is just you cannot use the entire process.env
object as dotenv-webpack
does not allow it showing you MISSING_ENV_VAR
instead.
If you chnange line 12 in your src\Layout.vue
as follows:
- return process.env
+ return process.env.VUE_APP_VAR
you get your 123
value of the variable in your Vue app.
The reason is at the time of building your application with webpack dotenv-webpack
replaces the explicit string process.env.SOME_EXPLICIT_VARIABLE_NAME_HERE
existing in your code with the actual value of SOME_EXPLICIT_VARIABLE_NAME_HERE
if that exist in the Webpack JS environment's actual process.env
object.
This means you never get the entire process.env
object accessible in your webpack bundle, and the bundle does not comprise the variable names like VUE_APP_VAR=123
. This is the goal of dotenv-webpack
.
You can get some more details in my answer here.
PS: DefinePlugin
, being returned in the build config, could override process.env
. It does so in Vue CLI (which is hardly justifiable). So its effect there sould be neutralized manually for dotenv-webpack
to work within Vue CLI (v4 and v5) applications as expected.
Upvotes: 1