我试图弄清楚如何只对前端实际使用的块/块使用css。使用当前的设置,所有内容都绑定到我的build/frontend.css文件中,所以只需使用多个块中的一个就可以加载所有的css,因为它都在构建的frontend.css文件中。但是,如果我只使用英雄块,我只希望英雄css被加载到前端,而不是整个css文件。
以下是我的文件夹结构的基本概念
build
frontend.css
frontend.js
src
index.js
frontend.css
frontend.js
hero
-index.js
-index.css
callToAction
-index.js
-index.css
index.php在我的php文件中:
// only load the frontend css and js if there is a block using it
add_filter( 'should_load_separate_core_block_assets', '__return_true' );
add_action('init', 'custom_register_gutenberg_blocks');
function custom_register_gutenberg_blocks() {
// register scripts - backend
wp_register_script('custom-blocks-editor-scripts',
plugins_url('build/index.js', __FILE__),
array('wp-blocks', 'wp-i18n', 'wp-editor'),
filemtime( plugin_dir_path( __FILE__ ) . 'build/index.js') // version
);
// register scripts - frontend
wp_register_script('custom-blocks-frontend-scripts',
plugins_url('build/frontend.js', __FILE__),
array('wp-blocks', 'wp-i18n', 'wp-editor'),
);
// register styles - backend
wp_register_style('custom-blocks-editor-style',
plugins_url('build/index.css', __FILE__),
array('wp-edit-blocks'),
);
// register styles - frontend
wp_register_style('custom-blocks-frontend-styles',
plugins_url('build/frontend.css', __FILE__),
);
// Allow inlining small stylesheets on the frontend if possible.
wp_style_add_data( 'custpm-blocks-frontend-styles', 'path', dirname( __FILE__ ) . '/frontend.css' );
register_block_type('custom/hero', array(
'editor_script' => 'custom-blocks-editor-scripts',
'editor_style' => 'custom-blocks-editor-style',
'style' => 'custom-blocks-frontend-styles',
'script' => 'custom-blocks-frontend-scripts',
'render_callback' => 'custom_hero'
));
function custom_hero($attributes) {
ob_start(); ?>
<div>
Content output here
</div>
<?php return ob_get_clean();
}
}然后,例如,在英雄块中,我从同一个文件夹加载css文件。
src/hero/index.js
import "./index.css";
import { registerBlockType } from "@wordpress/blocks";
registerBlockType("custom/hero", {
// edit: (props) => {}
// save: (props) => {}
});因此,js文件只是从它们的特定块文件夹加载css,但在php中,我从构建文件夹调用frontend.css文件。
发布于 2021-11-22 16:58:38
要为每个块获取单独的文件,您需要带上你自己的webpack配置
像这样简单的一个应该能起作用:
const defaultConfig = require('@wordpress/scripts/config/webpack.config');
module.exports = {
...defaultConfig,
entry: {
'hero': './src/hero',
'call-to-action': './src/callToAction',
},
};Ryan有一个例子回购和一个通过视频浏览它的创作 (该链接指向创建自定义webpack配置的部分)。
更新:原来可以在没有自定义webpack配置的情况下获得单独的包,但是(使用@wordpress/scripts的19.1.0版本),只有当入口点有不同的文件名时,它才能工作。也就是说,如果另一个文件的名称相同,它将无法包含一个文件。例如,这将构建,但foo/index.js将被忽略:
"build:custom": "wp-scripts build foo/index.js bar/index.js"鉴于这将如预期的那样起作用:
"build:custom": "wp-scripts build foo/foo.js bar/bar.js"https://wordpress.stackexchange.com/questions/398379
复制相似问题