Can anyone explain how the environment variables work for webpack vue-cli project? There is this line in the config.js.
var env = process.env.APP_ENV || 'development'
I have deployed my app via Laravel Forge (https://forge.laravel.com/servers) and I have a chance to edit env file there directly. I have added this into my environment file but it's not working?
APP_ENV=production
Environment file is read without problem from the PHP app...
Env variables in vue-cli are only used during build time (npm run dev/ npm run build), not runtime. So when you add any env variables in your server and expect them to be accessible to the JavaScript when your app runs in production, you are mistaken.
@LinusBorg is there a good way to pass env data to the javascript?
hi @happilymarrieddad
for build time env data passing you can add this line in the module.exports from ./build/webpack.base.conf.js (so it's included in dev, test and prod confs):
module.exports = {
...
plugins: [
new webpack.DefinePlugin({
'process.env': {
'API_BASE_PATH': JSON.stringify(process.env.API_BASE_PATH)
}
})
],
....
then in your code you can use it: const apiBasePath = process.env.API_BASE_PATH || 'http://localhost:3333/api/admin'
If you want runtime env variable replacement you could build a simple server side script (in nodejs, php or your lang of choice) that serves a config file dynamically. The problem with that is that if you need some bootstrapping related config (like what the host of the API is) you end up in a chicken and egg situation).
@andreiashu thanks so much man!
Check out https://webpack.js.org/plugins/environment-plugin/ to avoid the awkward JSON.stringify and extra quotes. You can just specify which process.env keys you want to expose to the frontend.
for example: new webpack.EnvironmentPlugin(['NODE_ENV', 'DEBUG'])
How do you change the environment variable from CLI? Is this possible?
Example: npm run dev HOST=custom-host.dev PORT=8081
They are written before the command, not after it
Sure!
On Windows you need to do:
SET HOST=custom.dev
SET PORT=8081
npm run dev
That is all! Thank you!
Most helpful comment
@LinusBorg is there a good way to pass env data to the javascript?