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

问题描述

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

enter image description here

如何让它替换文件而不是复制文件?特别是当我在本地运行 yarn encore dev --watch 时?

这是我的 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 即可删除无用文件。

CleanWebpack 插件

Symfony Encore 使用 clean-webpack-plugin 作为它的 cleanupOutputBeforeBuild() 选项。但是,这效果不佳,因为 loading fails during build time

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...