laravel-mix / laravel-mix

The power of webpack, distilled for the rest of us.
MIT License
5.26k stars 806 forks source link

Pass Options to Webpack-CLI #3350

Open marcelaerts opened 1 year ago

marcelaerts commented 1 year ago

Pass Options to Webpack-CLI https://laravel-mix.com/docs/6.0/cli#pass-options-to-webpack-cli npx mix -- --env foo=bar

I'm trying to pass options to Webpack CLI to access them inside my webpack.mix.js. I want to be able to execute different parts of my script according to the value. For some reason I can't access them.

console.log(process.env.foo) returns undefined. Can someone help?

ojvribeiro commented 1 year ago

I don't know if it is related or I should open a new issue, but I want to run the project using HMR via CLI (via Webpack commands), I can't make it to work though.

I'm trying to use the find-free-port package in my Laravel Mix project by running the following in a standalone project (outside Laravel):

mix watch --hot -- --host localhost --port [PORT]

Where the [PORT] is passed dynamically via JavaScript.

Say the port is set to 3000. The server is raised and the project runs, but without the HMR. I noticed that the hot file generated by Mix still contains the default http://localhost:8080 and that's the reason HMR does not work on 3000.

Yes, I tried to set it via the options method in the webpack.mix.js file, but the find-free-port returns a Promise with the available port, which Laravel Mix can't wait because it raises the HMR server before the Promise is fulfilled, thus keeping the default 8080 port. That's why I'm trying to use the CLI instead, and run it before HMR server is raised.

ojvribeiro commented 1 year ago

console.log(process.env.foo) returns undefined.

It seems Webpack enviroment vars are accessed via the env variable (like env.MY_VARIABLE). But it doesn't seem to work on Laravel Mix either. It's also returning undefined.

ojvribeiro commented 1 year ago

My solution was using the yargs package:

npm i yargs

The command:

mix watch --hot -- --port=3000

The mix file:

const mix = require('laravel-mix')
const { argv } = require('yargs')

mix
  .options({
    hmrOptions: {
      host: 'localhost',
      port: argv.port,
    },
  })