leuverink / asset-injector
自动将包资源注入页面
2.0.0
2024-09-26 15:13 UTC
Requires
- php: ^8.1
- illuminate/contracts: ^10|^11
- illuminate/support: ^10|^11
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3
- larastan/larastan: ^2.9
- laravel/pint: ^1
- orchestra/testbench: ^9
- pestphp/pest: ^2.35
- squizlabs/php_codesniffer: ^3
- tightenco/duster: ^3
- tightenco/tlint: ^9
README
使用自动资源注入简化 Laravel 包的开发。
此包允许您无缝地将 JavaScript 和 CSS 插入到 web 响应中,而无需您的包用户手动包含 🚀
安装
通过 Composer 安装包
composer require leuverink/asset-injector
使用方法
- 安装后,您需要创建一个
AssetInjector
实现。
namespace YourPackage; use Leuverink\AssetInjector\Contracts\AssetInjector; class InjectAssets implements AssetInjector { // Used to identify your assets in the HTML response public function identifier(): string { return 'MY_PACKAGE'; } // You can opt in to asset injection by implementing your own checks. // For example if a package user can control this via config file, or when your end user hits a middleware public function enabled(): bool { return true; } // Will inject return value in head tag or before html close if no head is present public function inject(): string { $js = file_get_contents(__DIR__ . '/../build/my-package.js'); $css = file_get_contents(__DIR__ . '/../build/my-package.css'); return <<< HTML <script type="module">{$js}</script> <style>{$css}</style> HTML; } }
- 在您的包的 Service Provider 中注册该实现。
namespace YourPackage; use Illuminate\Support\ServiceProvider as BaseServiceProvider; use Leuverink\AssetInjector\AssetManager; use YourPackage\InjectAssets; class ServiceProvider extends BaseServiceProvider { public function boot() { AssetManager::register(new InjectAssets); } }
工作原理
- 资源会自动包含在完整的页面响应中(不是部分 HTML 响应)。
- 如果存在
<head>
标签,资源将注入其中。否则,它们将在关闭的</html>
标签之前插入。 identifier()
方法有助于防止重复的资源注入。- 使用
enabled()
方法实现基于您包配置的条件性资源注入。 - 通过修改
inject()
方法来自定义注入的内容。
开发
使用以下命令进行开发
composer lint # run all linters composer fix # run all fixers composer analyze # run static analysis composer baseline # generate static analysis baseline composer test # run test suite
许可证
此包是开源软件,根据 MIT 许可证授权。