stellarwp/assets

用于在WordPress中管理资产注册和排队的库。

1.2.9 2024-08-08 20:46 UTC

README

Tests Static Analysis

用于在WordPress中管理资产注册和排队的库。

目录

安装

建议您通过 Composer 将 Assets 作为项目依赖项安装

composer require stellarwp/assets

我们实际上推荐使用 Strauss 将此库包含到您的项目中。

幸运的是,将 Strauss 添加到您的 composer.json 只比添加一个典型依赖项稍微复杂一些,所以请查看我们的 strauss 文档

示例说明

由于建议使用 Strauss 为此库的命名空间添加前缀,所有示例都将使用 Boomshakalaka 命名空间前缀。

配置

此库在使用其功能之前需要一些配置。配置是通过 Config 类完成的。

use Boomshakalaka\StellarWP\Assets\Config;

add_action( 'plugins_loaded', function() {
	Config::set_hook_prefix( 'boom-shakalaka' );
	Config::set_path( PATH_TO_YOUR_PROJECT_ROOT );
	Config::set_version( YOU_PROJECT::VERSION );

	// Optionally, set a relative asset path. It defaults to `src/assets/`.
	// This path is where your JS and CSS directories are stored.
	Config::set_relative_asset_path( 'src/assets/' );
} );

注册和排队资产

有许多可用于处理资产的可选项

简单示例

对于所有示例,假设正在使用以下 use 语句

use Boomshakalaka\StellarWP\Assets\Asset;

简单注册

Asset::add( 'my-style', 'css/my-style.css' )
	->register();

基于URL的资产注册

Asset::add( 'remote-js', 'https://someplace.com/script.js' )
	->register();

指定版本

默认情况下,资产继承 Config::get_version() 中设置的版本,但您可以手动指定版本

Asset::add( 'another-style', 'css/another.css', '1.2.3' )
	->register();

指定根路径

默认情况下,根据 Config::get_path() 中设置的值从您项目的根路径搜索/找到资产,但您可以手动指定根路径

Asset::add( 'another-style', 'css/another.css', null, $my_path )
	->register();

无文件扩展名的资产

如果您需要注册一个没有扩展名的资产,可以通过手动设置资产类型来做到,如下所示

Asset::add( 'extension-less', 'https://someplace.com/a/style' )
	->set_type( 'css' )
	->register();

// or:

Asset::add( 'extension-less', 'https://someplace.com/a/script' )
	->set_type( 'js' )
	->register();

设置优先级顺序

您可以通过 ::set_priority() 方法设置排队脚本的特定顺序。此方法接受一个整数,其工作方式与 WP 中动作/过滤器的优先级相似

Asset::add( 'my-style', 'css/my-style.css' )
	->set_priority( 20 )
	->register();

依赖关系

如果您的资产有依赖项,可以像这样指定它们

Asset::add( 'script-with-dependencies', 'js/something.js' )
	->set_dependencies( 'jquery', 'jquery-ui', 'some-other-thing' )
	->register();

您还可以指定依赖项作为返回数组依赖项的可调用,如下所示

Asset::add( 'script-with-dependencies', 'js/something.js' )
	->set_dependencies( function() {
		return [ 'jquery', 'jquery-ui', 'some-other-thing' ];
	} )
	->register();

请注意,可调用将在资产 排队 时执行。

在动作上自动排队

要指定何时排队资产,您可以指示如下

Asset::add( 'yet-another-style', 'css/yet-another.css' )
	->enqueue_on( 'wp_enqueue_scripts' )
	->register();

综合CSS示例

以下示例显示了在资产注册期间可用的所有选项

use Boomshakalaka\StellarWP\Assets\Asset;

Asset::add( 'my-asset', 'css/some-asset.css', $an_optional_version, $an_optional_path_to_project_root )
	->add_style_data( 'rtl', true )
	->add_style_data( 'suffix', '.rtl' )
	->add_to_group( 'my-assets' ) // You can have more than one of these.
	->call_after_enqueue( // This can be any callable.
		static function() {
			// Do something after the asset is enqueued.
		}
	)
	->enqueue_on( 'wp_enqueue_scripts', 20 ) // The second arg is optional and can be set separately via `::set_priority()`.
	->set_condition( // This can be any callable that returns a boolean.
		static function() {
			return is_front_page() || is_single();
		}
	)
	->set_dependencies( 'some-css' ) // Each dependency becomes a parameter in this method.
	->set_media( 'screen' )
	->set_min_path( 'src/assets/build/' )
	->set_path( 'src/assets' )
	->set_type( 'css' ) // Technically unneeded due to the .js extension.
	->register();

综合JS示例

use Boomshakalaka\StellarWP\Assets\Asset;

Asset::add( 'my-asset', 'js/some-asset.js', $an_optional_version, $an_optional_path_to_project_root )
	->add_localize_script( // You can have more than one of these.
		'some_js_variable',
		[
			'color' => 'blue',
		]
	)
	->add_to_group( 'my-assets' ) // You can have more than one of these.
	->call_after_enqueue( // This can be any callable.
		static function() {
			// Do something after the asset is enqueued.
		}
	)
	->enqueue_on( 'wp_enqueue_scripts', 20 ) // The second arg is optional and can be set separately via `::set_priority()`.
	->print_before( '<b>Before</b>' )
	->print_after( '<b>After</b>' )
	->set_as_async( true )
	->set_as_deferred( true )
	->set_as_module( true )
	->set_condition( // This can be any callable that returns a boolean.
		static function() {
			return is_front_page() || is_single();
		}
	)
	->set_dependencies( 'jquery' ) // Each dependency becomes a parameter in this method.
	->set_min_path( 'src/assets/build/' )
	->set_path( 'src/assets' )
	->set_type( 'js' ) // Technically unneeded due to the .js extension.
	->register();

手动排队

有时您不想将资产设置为在特定动作上自动排队。在这些情况下,您可以触发手动排队

use Boomshakalaka\StellarWP\Assets\Assets;

// Enqueue a single asset:
Assets::instance()->get( 'my-style' )->enqueue();

// Enqueue multiple assets:
Assets::instance()->enqueue(
	[
		'my-style',
		'my-script',
		'something-else',
	]
);

/**
 * If you want to force the enqueue to happen and ignore any conditions,
 * you can pass `true` to the second argument.
 */
Assets::instance()->enqueue(
	[
		'my-style',
		'my-script',
		'something-else',
	],
	true
);

// And here's how you can do it with a specific asset:
Assets::instance()->get( 'my-style' )->enqueue( true );

排队整个组

如果您有一组要排队的资产,可以这样做

use Boomshakalaka\StellarWP\Assets\Assets;

// You can do single groups:
Assets::instance()->enqueue_group( 'group-name' );

// or multiple:
Assets::instance()->enqueue_group( [ 'group-one', 'group-two' ] );

// or if you want to force the enqueuing despite conditions:
Assets::instance()->enqueue_group( 'group-name', true );

与注册的 Assets 一起工作

exists()

您可以使用 ::exists() 方法检查是否已使用此库注册了资产。此方法接受资产 slug 作为参数并返回一个 bool

use Boomshakalaka\StellarWP\Assets\Asset;
use Boomshakalaka\StellarWP\Assets\Assets;

Asset::add( 'my-asset', 'js/some-asset.js' )->register();

$assets = Assets::instance();
$assets->exists( 'my-asset' ); // true
$assets->exists( 'another-asset' ); // false

get()

您可以通过调用::get()方法检索已注册的资产对象。此方法需要一个资产别名作为参数,并返回一个Asset对象或null

use Boomshakalaka\StellarWP\Assets\Asset;
use Boomshakalaka\StellarWP\Assets\Assets;

Asset::add( 'my-asset', 'js/some-asset.js' )->register();

$assets    = Assets::instance();
$asset_obj = $assets->get( 'my-asset' );

remove()

您可以通过调用::remove()方法从注册和队列中删除资产。此方法需要一个资产别名作为参数,并返回一个Asset对象或null

use Boomshakalaka\StellarWP\Assets\Asset;
use Boomshakalaka\StellarWP\Assets\Assets;

Asset::add( 'my-asset', 'js/some-asset.js' )->register();

$assets    = Assets::instance();
$assets->get( 'my-asset' )->enqueue();

// This will wp_dequeue_*() the asset and remove it from registration.
$assets->remove( 'my-asset' );

高级主题

压缩文件

默认情况下,如果您注册了资产且未启用SCRIPT_DEBUG,如果与原始文件位于同一目录中,将动态使用未压缩文件。但是,您可以指定一个不同的路径来查找未压缩的资产。

以下示例将在src/assets/build/目录中查找js/some-asset.min.js(注意文件名的变化)

Asset::add( 'my-asset', 'js/some-asset.js' )
	->set_min_path( 'src/assets/build/' )
	->register();

条件排队

您通常不会希望在每次页面加载时都入队一个资产。幸运的是,您可以使用::set_condition()方法指定资产应该何时入队。此方法需要一个可调用的函数,该函数应返回一个布尔值,表示是否应该入队该资产。

use Boomshakalaka\StellarWP\Assets\Asset;

// Simple condition.
Asset::add( 'my-asset', 'css/some-asset.css' )
	->set_condition( 'is_single' )
	->register();

// Class-based method.
Asset::add( 'my-asset', 'css/some-asset.css' )
	->set_condition( [ $my_class, 'my_method_that_returns_boolean' ] )
	->register();

// Anonymous function.
Asset::add( 'my-asset', 'css/some-asset.css' )
	->set_condition( static function() {
		// You can do whatever you want here as long as it returns a boolean!
		return is_single() || is_home();
	} )
	->register();

在排队发生之后触发回调

有时您需要知道入队何时发生。您可以使用::call_after_enqueue()方法指定一个回调,在入队发生时触发。与::set_condition()方法类似,此方法也需要一个可调用的函数。

use Boomshakalaka\StellarWP\Assets\Asset;

// Simple function execution.
Asset::add( 'my-asset', 'css/some-asset.css' )
	->call_after_enqueue( 'do_some_global_function' )
	->register();

// Class-based method.
Asset::add( 'my-asset', 'css/some-asset.css' )
	->call_after_enqueue( [ $my_class, 'my_callback' ] )
	->register();

// Anonymous function.
Asset::add( 'my-asset', 'css/some-asset.css' )
	->call_after_enqueue( static function() {
		// Do whatever in here.
	} )
	->register();

输出JS数据

如果您希望在入队后向页面输出JS数据(类似于wp_localize_script()),可以使用::add_localize_script()方法。此方法接受两个参数:第一个是输出的JS变量的名称,第二个参数是要分配给JS变量的数据。您可以多次调用此方法!

use Boomshakalaka\StellarWP\Assets\Asset;

Asset::add( 'my-asset', 'css/some-asset.css' )
	->add_localize_script(
		'boomshakalaka_animal',
		[
			'animal' => 'cat',
			'color'  => 'orange',
		]
	)
	->add_localize_script(
		'boomshakalaka_food',
		[
			'breakfast' => 'eggs',
			'lunch'     => 'sandwich',
			'dinner'    => 'enchiladas',
		]
	)
	->register();

如果您使用点符号指定对象名称,则该对象将“合并”到页面上的其他预存对象中。在以下示例中,将创建boomshakalaka.project对象,然后向其中添加firstScriptDatasecondScriptData对象。

use Boomshakalaka\StellarWP\Assets\Asset;

Asset::add( 'my-first-script', 'js/first-script.js' )
	->add_localize_script(
		'boomshakalaka.project.firstScriptData',
		[
			'animal' => 'cat',
			'color'  => 'orange',
		]
	)
	->register();

Asset::add( 'my-second-script', 'js/second-script.js' )
	->add_localize_script(
		'boomshakalaka.project.secondScriptData',
		[
			'animal' => 'dog',
			'color'  => 'green',
		]
	)
	->register();

Asset::add( 'my-second-script-mod', 'js/second-script-mod.js' )
	->add_localize_script(
		'boomshakalaka.project.secondScriptData',
		[
			'animal' => 'horse'
		]
	)
	->register();

输出结果将是

<script id="my-first-script-ns-extra">
	window.boomshakalaka = window.boomshakalaka || {};
	window.boomshakalaka.project = window.boomshakalaka.project || {};
	window.boomshakalaka.project.firstScriptData = Object.assign(
		window.boomshakalaka.project.firstScriptData || {},
		{ "animal": "cat", "color": "orange" }
	);
</script>
<script src="https://someplace.com/wp-content/plugins/my-plugins/js/first-script.js" id="my-first-script-js"></script>
<script id="my-second-script-ns-extra">
	window.boomshakalaka = window.boomshakalaka || {};
	window.boomshakalaka.project = window.boomshakalaka.project || {};
	window.boomshakalaka.project.secondScriptData = Object.assign(
		window.boomshakalaka.project.secondScriptData || {},
		{ "animal": "dog", "color": "green" }
	);
</script>
<script src="https://someplace.com/wp-content/plugins/my-plugins/js/second-script.js" id="my-second-script-js"></script>
<script id="my-second-script-mod-ns-extra">
	window.boomshakalaka = window.boomshakalaka || {};
	window.boomshakalaka.project = window.boomshakalaka.project || {};
	window.boomshakalaka.project.secondScriptData = Object.assign(
		window.boomshakalaka.project.secondScriptData || {},
		{ "animal": "horse" }
	);
</script>
<script src="https://someplace.com/wp-content/plugins/my-plugins/js/second-script-mod.js"
		id="my-second-script-mod-js"></script>

注意my-second-script-mod处理程序将覆盖boomshakalaka.project.secondScriptData.animal中特定的嵌套键,同时在boomshakalaka.project.secondScriptData对象中保留其他键。

使用可调用提供本地化数据

如果您需要动态提供本地化数据,可以使用可调用的函数来实现。当资产入队时将调用此可调用的函数,并使用返回值。可调用的函数将资产作为第一个参数传递,并应返回一个数组。

Asset::add( 'my-script', 'js/some-asset.js' )
	->add_localize_script(
		'boomshakalaka.project.myScriptData',
		function( Asset $asset ) {
			return [
				'animal' => 'cat',
				'color'  => 'orange',
			];
		}
	)
	->register();

任何有效的可调用的函数都可以使用,包括上面示例中使用的闭包。

在输出JS资产前后输出内容

有时您可能希望在输出JS资产之前或之后立即输出标记或文本。您可以使用::print_before()::print_after()来实现这一点。

use Boomshakalaka\StellarWP\Assets\Asset;

Asset::add( 'my-asset', 'js/some-asset.js' )
	->print_before( '<b>Before</b>' )
	->print_after( '<b>After</b>' )
	->register();

样式元数据

资产支持向样式表添加元数据。这是通过::add_style_data()方法实现的。此方法接受两个参数:第一个是元数据的名称,第二个是元数据的值。您可以多次调用此方法。

这与wp_style_add_data()函数类似。

use Boomshakalaka\StellarWP\Assets\Asset;

Asset::add( 'my-asset', 'css/some-asset.css' )
	->add_style_data( 'rtl', true )
	->add_style_data( 'suffix', '.rtl' )
	->register();