symfony - 在我的 Symfony 项目中使用 Webpack encore 进行资产管理
问题描述
我.enableVersioning()
在我的 Symfony Webpack Encore 上使用。这与环境类型无关。然而,我在本地编译中注意到的一个问题是 CSS/JS 资产正在创建同一文件的重复版本项。这是一个例子:
如何让它替换文件而不是复制它?特别是当我在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.json
和entrypoints.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()
选项。但是,这并不能很好地工作,因为在构建期间加载失败。
如果您将它作为插件安装在您的项目中,您将获得更多配置选项。安装很简单,只需运行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();
推荐阅读
- c++ - 我需要一个 Person 类型的循环双向链表,但我不断收到错误,我不明白为什么
- testing - 是否可以播放视频并在 UFT 中记录时间戳?
- python - 以特定格式提取 Excel 数据作为 python 文件的输入
- html - 添加文本会将整个 div 向下移动数百像素?
- captcha - 使用 pytesseract 从验证码中提取文本
- azure-devops - 在 Azure 存储帐户中上传 Blob 时出错
- javascript - 返回 If 语句
- postgresql - pq: "$1" Postgres + go 处或附近的语法错误
- android - 什么时候,为什么在android中使用广播接收器JobScheduler和服务请举例说明
- sql - 如何删除每个日期具有重复值的记录