becklyn/assets-bundle

为 symfony 项目提供高性能的资产处理。

安装次数: 12,936

依赖项: 2

建议者: 1

安全性: 0

星标: 6

关注者: 4

分支: 3

开放问题: 0

类型:symfony-bundle

2.7.3 2022-02-21 11:37 UTC

README

为 symfony 项目提供高性能的资产处理。

这个包是 symfony/asset 的一个简化和专门的替代品。

安装

composer require "becklyn/assets-bundle"

然后在你的 AppKernel / bundles.php 中添加这个包。

加载路由(最好只在 dev 中加载)

becklyn_assets:
    resource: "@BecklynAssetsBundle/Resources/config/routes.yaml"
    prefix: /

要使用资产的静态压缩,请安装 zopfligzip

apt install zopfli
# or
brew install zopfli

信息/目的

此包旨在提供一种透明处理资产长期缓存的方法。

入口点的所有资产都复制(可能转换)到 public/assets/,文件名也修改,以便它们包含给定文件的哈希值。它还提供了 Twig 函数,以便在 symfony 应用程序中透明地使用这些转换后的路径。

在 Twig 中,原始文件名提供给 asset* 函数,它会自动生成哈希文件名的 HTML 引用。

警告:在清除缓存时,目录 public/assets/ 将被完全清空,因此它应该仅由该包管理。

所有对 assets/ 目录的请求都可以长期缓存,例如使用远期到期日期或甚至 immutable 头部。

使用方法

资产生成和准备是自动完成的。在清除缓存和预热或遇到空缓存时按需生成。

在配置中定义了命名空间到目录的映射。然后使用 @{namespace}/{path} 语法使用这些命名空间来检索这些文件的路径。

becklyn_assets:
    entries:
        bundles: "public/bundles"

在 Twig 中,可以使用以下函数

{# automatically generates the <script></script> tags #}
{{ assets_js([
    "@bundles/app/js/bootstrap.js",
    "@bundles/app/js/app.js",
]) }}

{# automatically generates the <link> tags #}
{{ assets_js([
    "@bundles/app/css/bootstrap.css",
    "@bundles/app/css/app.css",
]) }}

{# just returns the URL #}
<img src="{{ asset("@bundles/app/img/logo.svg") }}" alt="Company Logo">

资产处理

当前包中只包含一个资产处理器。资产处理器根据文件扩展名选择,并应转换给定的文件内容。它们不应该改变文件本身(例如,压缩),但应调整导入路径(例如 CSS 中的 url(...))到新路径。

当前注册的处理器

警告:资产处理器使用来自 AssetCache 的路径。这意味着存在竞争条件,因为处理器只能重写已添加到缓存中的文件的路径。因此,带有处理器的文件将被延迟处理,并且只有在所有其他文件完成(至少使用命令或缓存预热器)之后才会处理。如果带有处理器的文件相互依赖,仍然可能存在竞争条件。

配置

所有配置值及其描述和默认值

becklyn_assets:
    # the entry points. Maps the namespace to the directory (relative to `%kernel.project_dir%`)
    # -> is required
    entries:
        bundles: "public/bundles"
        app: "assets"
        
    # the absolute path to the `public/` (or `web/`) directory
    public_path: '%kernel.project_dir%/public' 
    # relative path to the directory, where the assets are copied to (relative to `public_path`)
    output_dir: 'assets' 
    # allow crossorigin assets e.g needed for basic auth if using safari browser
    allow_cors: true

命令

becklyn:assets:reset

该包提供了一个命令来清除和预热缓存。

# clear + warmup
php bin/console becklyn:assets:reset

# only clear
php bin/console becklyn:assets:reset --no-warmup

通常不需要这些命令,因为该包会自动注册为 缓存清除器缓存预热器

becklyn:assets:namespaces

此命令将打印所有已注册命名空间的概述。如果你在配置之外程序化地注册路径,这将特别有用。

nginx 集成

由于文件名是从内容派生的,因此您的项目可以无限期地缓存导出的资产。

location /assets {
    add_header Cache-Control "public, max-age=31536000, immutable";
    add_header Vary "Accept-Encoding";
    log_not_found off;
    
    # only activate if it is supported
    gzip_static on;
    
    # be sure to add all security headers (like X-Frame-Options and HSTS or X-Content-Type-Options here as well)    
}