Webpack Encore - 在 PHP 中获取版本化文件

Webpack Encore - Get versionned files in PHP

我最近安装了带有 Webpack Encore 的 Symfony 4。 我使用一些静态资产通过 TCPDF 制作 PDF。 为此,我曾经使用路径获取图像,但是使用 Webpack Encore 版本控制,文件名不同,所以我无法通过这种方式获取图像。 是否有解决方案来保持版本控制并在 PHP 中访问这些图像?

PHP :

$logourl = trim("../public/build/images/tst_noir.png");
$pdf->Image($logourl, 135, 10.8, 42, 0);

Webpack app.js :

require('../images/tst_noir.png');

Webpack-config.js :

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

Encore
.setOutputPath('public/build/')
.setPublicPath('http://localhost/xxx/public/build')
.setManifestKeyPrefix('build/')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
.autoProvidejQuery()
.addEntry('app', './assets/js/app.js');

module.exports = Encore.getWebpackConfig();

如果您有用于网站上使用的资产设置的 Symfony 配置,您可以使用 assets.packages 包来获取文件的最终 display-ready URLs :

use Symfony\Component\Asset\Package;
use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy;

$package = new Package(new EmptyVersionStrategy());

// Absolute path
echo $package->getUrl('/image.png');
// result: /image.png

// Relative path
echo $package->getUrl('image.png');
// result: image.png

如果 Symfony 和 Webpack 配置(或直接设置组件)已经到位,还应处理版本控制和 URL 前缀。

// webpack.config.js
if (Encore.isProduction()) {
    Encore.setPublicPath('https://my-cool-app.com.global.prod.fastly.net');
    Encore.setManifestKeyPrefix('build/');
}

在 Symfony 3.0 之前,templating.helper.assets 提供了大致相同的功能,但现在您更有可能使用 framework.assets.json_manifest_path: 配置。