在我的 Symfony 项目中使用 Webpack encore 进行资产管理

Asset management with Webpack encore in my Symfony project

我正在我的 Symfony Webpack Encore 上使用 .enableVersioning()。这与环境类型无关。但是,我在本地编译时注意到的一个问题是 CSS/JS 资产正在创建同一文件的重复版本化项目。这是一个例子:

如何获取它来替换文件而不是复制文件?尤其是当我 运行 yarn encore dev --watch locally?

这是我的 webpack.config.js 文件:

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();

当我开始使用 Webpack Encore 时(2017 年的某个时候),我创建了一个(非常简单的)Symfony 命令,它读取 manifest.jsonentrypoints.json 并删除这些文件中未提及的所有文件。我 运行 此命令作为部署的最后一步。我发现我的生产服务器有数百兆字节的旧文件。我认为像这样的命令应该是 Webpack (Encore) 的一部分,但现在还不是。

使用 Symfony 命令清除文件

此命令适用于 Symfony 5.3 和 PHP 8.0:

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;

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;
    }
}

只是 运行 bin/console encore:purge-assets 删除无用的文件。

CleanWebpackPlugin

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

如果您将它作为插件安装在您的项目中,您将有更多的配置选项。安装很简单,只需 运行 yarn add --dev clean-webpack-pluginwebpack.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();