Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Teleogrid's avatar

Use Laravel mix to build for two differently configured targets - web (browser) and server (node)

Hi everyone,

I'm trying to compile javascript bundles for two different environments (server and browser version) simutaniously. But it looks like that with mix it is not possible to run webpack twice with two different configurations. I was trying to do it like this:

mix.webpackConfig({ target: 'web' })
    .js('resources/js/app.js', 'public/js');

mix.webpackConfig({ 
        target: 'node',
        externals: [ nodeExternals() ],
        node: {
            __dirname: false,
            __filename: false
        }
    })
    .js('server/src/server.js', 'public/js')
    .copy('public/js/server.js', 'server/dist/server.js')
    .then(() => {
        del('public/js/server.js');
    });

Any suggestions, how I could make this work?

0 likes
2 replies
Teleogrid's avatar

I'm not sure about how to use the link you've sent as a solution but I already figured out a solution. If someone else might be interested in how to do it:

First in package.jsonI added an alias that is running two node tasks with & in a row and then added custom environment variables process.env.target to each task. Each time my mix config is called I can then check the value of that environment variable within my webpack.mix.js and call the correct webpack config settings:

my package.js looks like this:

"scripts": {
        "dev": "npm run development & npm run webserver",
        "development": "[...] process.env.target=browser [...] --config=node_modules/laravel-mix/setup/webpack.config.js",
        "webserver": "[...] process.env.target=server [...] --config=node_modules/laravel-mix/setup/webpack.config.js"
}

my webpack.mix.js looks like this:

if (process.env.target === 'browser') {
    mix.webpackConfig({target: 'web'})
        .js('resources/js/app.js', 'public/js');
} else if (process.env.target === 'server') {
    mix.webpackConfig({
            target: 'node',
            externals: [nodeExternals()],
            node: {
                __dirname: false,
                __filename: false
            }
        })
        .js('webserver/src/webserver.js', 'public/js')
[...];
}
3 likes

Please or to participate in this conversation.