heimrichhannot/contao-encore-contracts

用于encore捆绑准备所需的一系列抽象。

1.0.2 2022-11-10 16:00 UTC

This package is auto-updated.

Last update: 2024-08-27 13:54:14 UTC


README

此包包含用于添加松散Encore捆绑支持的抽象。

用法

注册入口点

要注册encore入口点,请创建一个实现EncoreExtensionInterface的EncoreExtension类。

namespace HeimrichHannot\ExampleBundle\Asset;

use HeimrichHannot\EncoreContracts\EncoreEntry;
use HeimrichHannot\EncoreContracts\EncoreExtensionInterface;
use HeimrichHannot\ExampleBundle\HeimrichHannotExampleBundle;

class EncoreExtension implements EncoreExtensionInterface
{
    public function getBundle(): string
    {
        // Return the bundle class
        return HeimrichHannotExampleBundle::class;
    }

    public function getEntries(): array
    {
        // Return the bundle entries
        return [
            EncoreEntry::create('main-theme', 'assets/main/js/main-theme.js')
                ->setRequiresCss(true)
                ->setIsHeadScript(false),
            EncoreEntry::create('one-pager', 'assets/one-pager/js/one-pager.js')
                ->setRequiresCss(true),
            EncoreEntry::create('custom-head-js', 'assets/main/js/head.js')
                ->setIsHeadScript(true)
                // Define entries that will be removed from the global asset array
                ->addJsEntryToRemoveFromGlobals('colorbox')
                ->addCssEntryToRemoveFromGlobals('css-to-replace'),
        ];
    }
}

为当前页面添加入口点

要从您的代码中添加入口点(必须先注册),您可以使用PageAssetsTrait。它会检查是否已安装encore捆绑,如果是,则添加入口;否则,它将回退资产添加到contao全局资产数组。

使您的类实现ServiceSubscriberInterface并使用PageAssetsTrait(它已经实现了ServiceSubscriberInterface所需的方法)。之后只需调用$this->addPageEntrypoint(string $name, array $fallbackAssets = [])

use HeimrichHannot\EncoreContracts\PageAssetsTrait;
use Symfony\Contracts\Service\ServiceSubscriberInterface;

class FrontendController implements ServiceSubscriberInterface
{
    use PageAssetsTrait;
    
    public function __invoke()
    {
        $this->addPageEntrypoint(
            // Encore entry point name
            'contao-example-bundle', 
             // Optional: define fallback assets to use if encore bundle is not installed
            [
                'TL_CSS' => ['main-theme' => 'assets/main/dist/main-theme.min.css|static'],
                'TL_JAVASCRIPT' => [
                    'main-theme' => 'assets/main/dist/main-theme.min.js|static',
                    'some-dependency' => 'assets/some-dependency/some-dependency.min.js|static',
                ],
            ]
        );
    }
}