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.