Search code examples
phplaravelwebpackenvironment-variableslaravel-mix

How to pass env parameters to a Laravel Mix 6?


Is there some way to pass parameters to the laravel mix via the command line and get them in the webpack.mix.js file? For example, I added the line frontend-dev, but I can't get the "foo" variable after running "yarn run frontend-dev".

package.json

{
    "private": true,
    "scripts": {
        "development": "mix",
        "frontend-dev": "mix -- --env foo=frontend"
    },
    "devDependencies": {
        "axios": "^0.21",
        "laravel-mix": "^6.0.6",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14"
    }
}

webpack.mix.js

const mix = require('laravel-mix');

//console.log(process.env);
console.log(process.env.foo); //output: undefined

Solution

  • You can do it from the command line...

    npm run development --foo=frontend
    

    Then in webpack.mix.js, you can prefix your foo variable with npm_config_.

    console.log(process.env.npm_config_foo);
    

    Otherwise, if you want the value to come from your .env file, you may need to prefix your .env variable with MIX_, like MIX_FOO_VARIABLE=frontend.

    And then, in webpack.mix.js, you can do the following.

    console.log(process.env.MIX_FOO_VARIABLE);