Reputation: 31
Before upgrade to Laravel-Mix 6:
With this laravel mix version I was able to pass in environment variables to webpack.mix.js by running the npm scripts defined in package.json:
"dev": "cross-env NODE_ENV=development ENV_FILE=./.env.local node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
...
"production": "cross-env NODE_ENV=production ENV_FILE=./.env.production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
Then I could access the variable in webpack.mix.js, whose value depends on whether I was running on production or development mode:
let mix = require("laravel-mix");
mix.env(process.env.ENV_FILE);
This worked fine!
After upgrade to Laravel-Mix 6:
I followed the recommendations from the laravel documentation including the update of the npm scripts...
Following the instructions on the documentation how to pass in environment variables to Webpack CLI (please refer to https://laravel-mix.com/docs/6.0/cli#pass-options-to-webpack-cli), the npm scripts where then changed as follows:
"dev": "mix -- --env ENV_FILE=./.env.local",
"production": "mix --production -- --env ENV_FILE=./.env.production"
The problem is, that I cannot access the environment variable in webpack.mix.js anymore via process.env.ENV_FILE
. Its value is undefined...
I already checked out in node_modules/laravel-mix/setup/webpack.config.js through console.log, that the variable indeed was passed in:
const { assertSupportedNodeVersion } = require('../src/Engine');
module.exports = async (config) => {
assertSupportedNodeVersion();
console.log("ENV_FILE: ", config.ENV_FILE);
const mix = require('../src/Mix').primary;
require(mix.paths.mix());
await mix.installDependencies();
await mix.init();
return mix.build();
};
And by running for instance npm run dev
I can see the value logged out:
mix -- --env ENV_FILE=./.env.local
ENV_FILE: ./.env.local
So the question is, why I cannot access the environment variable in webpack.mix.js, and more importantly, how can I do it.
Thanks in advance for the help!
Upvotes: 3
Views: 1664
Reputation: 344
Laravel Mix 6 / Customize the Mix Configuration Path
There is no need to pass settings via env params anymore - simply specify different webpack.mix.js files for each script variation using --mix-config
option and incorporate any additional settings (statically) into these:
"dev": "mix --mix-config=webpack.mix.dev.js",
"production": "mix --mix-config=webpack.mix.prod.js --production"
etc. Of course you can then still require
a common webpack.mix.js
containing the actual mix logic.
Upvotes: 3