Laravel Mix: versioning of copied files & directories

Published 02 August 2021 11:22 (2-minute read)

Have you ever wanted to copy a directory using Laravel Mix, but you needed to version those copied files? This can be easily done by using this simple Laravel Mix task.

By default, Laravel Mix isn't running versioning on files that are copied during the same request (see for more information: https://github.com/JeffreyWay/laravel-mix/issues/270).

This is done for mix.combine() now. We still don't version copied files, but you can manually do so with mix.version(['path/to/file.js']); ~ (JeffreyWay, 8 Feb 2017)

But when you add the following script to your webpack.mix.js, it will add all files in the directories you define as a "to version" file.

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

// ....
const glob = require('glob');
const directoriesToCopy = ['assets'];
const publicDir = 'public/';
const resourcesDir = 'resources/';

directoriesToCopy.forEach(directory => mix.copyDirectory(resourcesDir + directory, publicDir + directory));

mix.version(
    [
        //'sw.js', // Other files that need versioning
    ]
        .concat(
            ...directoriesToCopy
                .map(directory => glob.sync('**/*', {cwd: resourcesDir + directory})
                .map(file => directory + '/' + file))
        )
        .map(file => publicDir + file)
);

When you ever update a file in the resources directory, it will be copied & versioned during the next deployment, and you don't need to worry about cache busting your CDN/clients. Laravel Mix will do this during the built process.

Robin Dirksen
Robin Dirksen

Follow me on Twitter, there I post web-related content, tips/tricks, and other interesting things.

On my blog, you can find articles that I've found useful or wanted to share with anyone else.

If you want to know more about this article or just want to talk to me, don't hesitate to reach out.

Webmention by Brady Renting
Brady Renting liked on 3rd August 2021
Webmention by Lars Koole
Lars Koole liked on 3rd August 2021
Webmention by Florian Wartner
Florian Wartner liked on 3rd August 2021
Webmention by Rob de Kort
Rob de Kort liked on 3rd August 2021
Legal