How to pass env parameters to a Laravel Mix 6?
Asked Answered
C

1

8

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
Coston answered 2/8, 2021 at 20:35 Comment(0)
B
10

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);
Broderic answered 2/8, 2021 at 20:48 Comment(1)
This doesn't work when using the mix command: $ mix --production --ieCompat=true error: unknown option '--ieCompat=true' and $ mix --production -- --ieCompat=true [webpack-cli] Error: Unknown option '--ieCompat=true'Venetian

© 2022 - 2024 — McMap. All rights reserved.