Asset management with Webpack encore in my Symfony project

Solution for Asset management with Webpack encore in my Symfony project
is Given Below:

I am using .enableVersioning() on my Symfony Webpack Encore. This is regardless of environment type. However one issue I noticed on local compiling is that CSS/JS assets are creating duplicate versioned items of the same file. Here is an example:

enter image description here

How do I get it to replace the file instead of duplicate it? Especially when I run yarn encore dev --watch locally?

Here is my webpack.config.js file:

const Encore = require('@symfony/webpack-encore');

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')
    // only needed for CDN's or sub-directory deploy
    //.setManifestKeyPrefix('build/')
    .copyFiles({
         from: './assets/images/',
         to: '[path][name].[hash:8].[ext]',
         context: './assets'
    })
    .copyFiles({
        from: 'node_modules/tinymce/skins',
        to: 'skins/[path]/[name].[ext]'
    })

    /*
     * ENTRY CONFIG
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if your JavaScript imports CSS.
     */
    .addEntry('currencyformatter', './assets/js/jquery.inputmask.min.js')
    .addEntry('base', './assets/js/app.js')
    .addEntry('homepage', './assets/js/homepage.js')
    .addEntry('tinymce', './assets/js/tinymce.js')
    .addEntry('email', './assets/js/email.js')

    // enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)
    // .enableStimulusBridge('./assets/controllers.json')

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()
    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps()
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning()//

    .configureBabel((config) => {
        config.plugins.push('@babel/plugin-proposal-class-properties');
    })

    // enables @babel/preset-env polyfills
    .configureBabelPresetEnv((config) => {
        config.useBuiltIns="usage";
        config.corejs = 3;
    })

    // enables Sass/SCSS support
    .enableSassLoader()

    // uncomment if you use TypeScript
    //.enableTypeScriptLoader()

    // uncomment if you use React
    //.enableReactPreset()

    // uncomment to get integrity="..." attributes on your script & link tags
    // requires WebpackEncoreBundle 1.4 or higher
    //.enableIntegrityHashes(Encore.isProduction())

    // uncomment if you're having problems with a jQuery plugin
    //.autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();

When I started to use Webpack Encore (somewhere in 2017) I created a (very simple) Symfony Command that reads manifest.json and entrypoints.json and deletes all files that not mentioned in those files. I run this command as the last step of my deployment. I found out that my production server had hundreds of megabytes with old files. I think a command like this should be part of Webpack (Encore), but it isn’t (yet).

Purge files with Symfony Command

This command will work with Symfony 5.3 and PHP 8.0:

use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
use SymfonyComponentFilesystemFilesystem;

final class PurgeAssetDirectoryCommand extends Command
{
    public static $defaultName="encore:purge-assets";
    protected static $defaultDescription = 'Purge useless assets';

    public function __construct(private Filesystem $filesystem, private string $projectDir)
    {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output) : int
    {
        $assetDir = $this->projectDir . '/public/assets/';

        $manifestFile = file_get_contents($assetDir . '/manifest.json');

        if (! $manifestFile) {
            return Command::FAILURE;
        }

        $exclude = json_decode($manifestFile, true, 512, JSON_THROW_ON_ERROR);

        $exclude[] = '/assets/entrypoints.json';
        $exclude[] = '/assets/manifest.json';

        $files = scandir($assetDir, 1);

        foreach ($files as $file) {
            if (in_array('/assets/' . $file, $exclude, true)) {
                continue;
            }

            if (is_dir($assetDir . $file)) {
                continue;
            }

            $this->filesystem->remove($assetDir . $file);
        }

        return Command::SUCCESS;
    }
}

Just run bin/console encore:purge-assets to remove useless files.

CleanWebpackPlugin

Symfony Encore uses clean-webpack-plugin for it the cleanupOutputBeforeBuild() option. However, this doesn’t work very well because loading fails during build time.

If you install it in your project as a plugin, you’ve got more configuration options. Installation is easy, just run yarn add --dev clean-webpack-plugin and it to your webpack.config.js:

const Encore = require('@symfony/webpack-encore');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    // ...
  .addPlugin(new CleanWebpackPlugin())
;

module.exports = Encore.getWebpackConfig();