Sunday, July 12, 2020

How to remove build files before another new build start on Laravel-Mix Webpack config file | Delete unused laravel chunk files | Clean dist folder before generating a new build - Laravel with ReactJS

Since we generate lot of builds with different hashed filenames, it is a good practice to delete the dist directory before running each build.
In laravel-mix webpack.mix.js is the configuration file we used for reactjs webpack configuration. What we have to do write some code to webpack.mix.js (located in based directory of project in my case)
const mix = require('laravel-mix');
const date = (new Date()).getTime();

const fs = require('fs');
const buildDir = './public/js/chunk/';
fs.readdir(path.resolve(buildDir), (err, files) => {
    if (err) {
        console.log(err);
    }
    else {
        files.forEach(function (file) {
            fs.unlink(path.resolve(buildDir + file), function () {
                console.log(buildDir + file + ' - deleted');
            });
        });
    }
});

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.react('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

mix.webpackConfig({
    output: {
        // Directory for junk files to {ROOT_DIR}/public/js
        chunkFilename: 'js/chunk/[name]-' + date + '.js'
    },
});

No comments:

Post a Comment