title: "开始使用 create-block" post_status: publish comment_status: open taxonomy: category: - gutenberg-docs post_tag: - Devenv - Getting Started - Repos
开始使用 create-block
WordPress 区块编辑器中的自定义区块通常通过插件注册,并由一组特定文件定义。@wordpress/create-block 包是一个官方支持的工具,用于搭建创建和注册区块所需的文件结构。它能生成启动项目所需的所有代码,并集成现代化的 JavaScript 构建设置(使用 wp-scripts),无需任何配置。
该工具包旨在帮助开发者遵循 WordPress 最佳实践,快速建立区块开发环境。
快速开始
安装
首先确保您的计算机已安装 Node.js 和 npm。如果尚未安装,请查阅 Node.js 开发环境指南。
您可以使用 create-block 在几乎任何地方搭建区块,然后在生成的插件文件夹内使用 wp-env。这将创建一个本地 WordPress 开发环境,并安装和激活您的新区块插件。
如果您已经设置了自己的本地 WordPress 开发环境,请使用终端导航到 plugins/ 文件夹。
运行以下命令来搭建一个示例区块插件:
npx @wordpress/create-block@latest todo-list
cd todo-list
提供的 slug(todo-list)定义了搭建的插件文件夹名称和内部区块名称。
导航到本地 WordPress 安装的插件页面,激活 "Todo List" 插件。示例区块随后将在编辑器中可用。
Basic usage
The create-block assumes you will use modern JavaScript (ESNext and JSX) to build your block. This requires a build step to compile the code into a format that browsers can understand. Luckily, the wp-scripts package handles this process for you. Refer to the Get started with wp-scripts for an introduction to this package.
When create-block scaffolds the block, it installs wp-scripts and adds the most common scripts to the block's package.json file. By default, those include:
{
"scripts": {
"build": "wp-scripts build",
"format": "wp-scripts format",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"packages-update": "wp-scripts packages-update",
"plugin-zip": "wp-scripts plugin-zip",
"start": "wp-scripts start"
}
}
These scripts can then be run using the command npm run {script name}. The two scripts you will use most often are start and build since they handle the build step.
When working on your block, use the npm run start command. This will start a development server and automatically rebuild the block whenever any code change is detected.
When you are ready to deploy your block, use the npm run build command. This optimizes your code and makes it production-ready.
See the wp-scripts package documentation for more details about each available script.
替代实现方案
交互模式
对于偏好引导式体验的开发者,create-block 包提供了交互模式。与上述示例中预先手动指定所有选项(如 slug)不同,此模式将逐步提示您输入信息。
要使用此模式,请运行以下命令:
npx @wordpress/create-block@latest
按照提示交互式地配置您的区块设置。
使用选项的快速启动模式
如果您已熟悉 create-block 的选项并希望获得更简化的设置,可以使用快速启动模式。这允许您直接在命令行中传递特定选项,无需交互式提示。
例如,要快速创建一个命名空间为 "my-plugin"、别名为 "my-block" 的动态区块,请使用以下命令:
npx @wordpress/create-block@latest --namespace="my-plugin" --slug="my-block" --variant="dynamic"
使用模板
create-block 包还支持使用模板,允许您基于预定义的配置和结构创建区块。当您有偏好的区块结构或需要构建多个配置相似的区块时,这尤其有用。
要使用模板,请指定 --template 选项,后跟模板名称或路径:
npx @wordpress/create-block --template="my-custom-template"
模板必须提前设置好,以便 create-block 包知道在哪里找到它们。在 create-block 文档 中了解更多信息,并查看 外部项目模板 指南。
Additional resources
- Using the create-block tool (Learn WordPress tutorial)
- @wordpress/create-block (Official documentation)
- @wordpress/scripts (Official documentation)