# 为区块编辑器使用 JavaScript

为区块编辑器开发区块通常涉及使用现代 JavaScript（ESNext 和 JSX），区块编辑器手册中的大多数示例都采用这些语法编写。

然而，这种形式的 JavaScript 必须转换为浏览器兼容的格式，因此需要构建步骤。这个过程会将 JavaScript 源代码和相关资源转换、打包并优化为适合生产环境的格式。

## 使用构建流程的 JavaScript

为区块开发使用构建流程能够释放现代 JavaScript 的全部潜力，便于使用 ESNext 和 JSX。

[ESNext](https://developer.mozilla.org/en-US/docs/Web/JavaScript/JavaScript_technologies_overview#standardization_process) 指的是 JavaScript 最新的语法和特性。[JSX](https://react.dev/learn/writing-markup-with-jsx) 是由 React 项目开发的语法扩展，它让你可以编写类似 HTML 的 JavaScript。

由于浏览器无法直接执行 ESNext 和 JSX，这些语法必须被转换成浏览器兼容的 JavaScript。

[webpack](https://webpack.js.org/concepts/why-webpack/) 是一个可插拔的工具，用于处理和打包 JavaScript 以实现浏览器兼容性。[Babel](https://babeljs.io/) 是 webpack 的一个插件，可将 ESNext 和 JSX 转换为标准的 JavaScript。

配置 webpack 和 Babel 可能具有挑战性，因此建议你使用 [`@wordpress/scripts`](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-scripts/) 包。该工具预先配置了这两者，从而简化了开发，因此你很少需要编写自定义的 webpack 或 Babel 配置。

入门介绍，请参阅 [wp-scripts 入门指南](/docs/getting-started/devenv/get-started-with-wp-scripts)。

### `wp-scripts` 概览

下图概述了使用 `wp-scripts` 包时的构建流程。它旨在开箱即用地适用于开发和[生产环境的标准配置](/docs/getting-started/devenv/get-started-with-wp-scripts#basic-usage)。

[![打开构建流程图](https://developer.wordpress.org/files/2023/11/build-process.png)](https://developer.wordpress.org/files/2023/11/build-process.png "打开构建流程图")

- **生产模式 (`npm run build`):** 在此模式下，`wp-scripts` 会编译你的 JavaScript，压缩输出以减少文件大小并提升浏览器加载速度。这非常适合将代码部署到线上站点。

- **开发模式 (`npm start`):** 此模式专为活跃开发而设计。它跳过压缩以便于调试，生成源映射以更好地追踪错误，并监视你的源文件变化。当检测到更改时，它会自动重新构建受影响的文件，让你能够实时看到更新。

`wp-scripts` 包还支持使用 JavaScript 模块，允许将代码分布在多个文件中，并在构建过程后生成精简的捆绑包。[block-development-example](https://github.com/WordPress/block-development-examples/tree/trunk/plugins/data-basics-59c8f8) GitHub 仓库提供了一些很好的示例。

<div class="callout callout-tip">
    在大多数情况下，无需进行自定义，但你可以提供一个 <a href="https://developer.wordpress.org/block-editor/reference-guides/packages/packages-scripts/#provide-your-own-webpack-config"><code>webpack.config.js</code></a> 文件，在使用 <code>wp-scripts</code> 时修改构建流程以满足你的需求。
</div>

## JavaScript without a build process

Integrating JavaScript into your WordPress projects without a build process can be the most straightforward approach in specific scenarios. This is particularly true for projects that don't leverage JSX or other advanced JavaScript features requiring compilation.

When you opt out of a build process, you interact directly with WordPress's [JavaScript APIs](/docs/reference-guides/packages) through the global `wp` object. This means that all the methods and packages provided by WordPress are readily available, but with one caveat: you must manually manage script dependencies. This is done by adding [the handle](/docs/contributors/code/scripts) of each corresponding package to the dependency array of your enqueued JavaScript file.

For example, suppose you're creating a script that registers a new block [variation](/docs/reference-guides/block-api/block-variations) using the `registerBlockVariation` function from the [`blocks`](/packages/blocks/README) package. You must include `wp-blocks` in your script's dependency array. This guarantees that the `wp.blocks.registerBlockVariation` method is available and defined by the time your script executes.

In the following example, the `wp-blocks` dependency is defined when enqueuing the `variations.js` file.

```php
function example_enqueue_block_variations() {
	wp_enqueue_script(
		'example-enqueue-block-variations',
		get_template_directory_uri() . '/assets/js/variations.js',
		array( 'wp-blocks' ),
		wp_get_theme()->get( 'Version' ),
		false
	);
}
add_action( 'enqueue_block_editor_assets', 'example_enqueue_block_variations' );
```

Then in the `variations.js` file, you can register a new variation for the Media & Text block like so:

```js
wp.blocks.registerBlockVariation(
	'core/media-text',
	{
		name: 'media-text-custom',
		title: 'Media & Text Custom',
		attributes: {
			align: 'wide',
			backgroundColor: 'tertiary'
		},
	}
);
```

For scripts that need to run in the Block Editor, make sure you use the [`enqueue_block_editor_assets`](https://developer.wordpress.org/reference/hooks/enqueue_block_editor_assets/) hook coupled with the standard [`wp_enqueue_script`](https://developer.wordpress.org/reference/functions/wp_enqueue_script/) function.

Refer to [Enqueueing assets in the Editor](/docs/how-to-guides/enqueueing-assets-in-the-editor) for more information.

<div class="callout callout-tip">
    Open your browser's dev tools and try running <code>wp.data.select('core/editor').getBlocks()</code> in the console when editing a post or when using the Site Editor. This command will return all available blocks.
</div>

## Additional resources

- [Package reference](/docs/reference-guides/packages)
- [Get started with wp-scripts](/docs/getting-started/devenv/get-started-with-wp-scripts)
- [Enqueueing assets in the Editor](/docs/how-to-guides/enqueueing-assets-in-the-editor)
- [WordPress package handles](/docs/contributors/code/scripts)
- [JavaScript reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript) | MDN Web Docs
- [block-development-examples](https://github.com/WordPress/block-development-examples) | GitHub repository
- [block-theme-examples](https://github.com/wptrainingteam/block-theme-examples) | GitHub repository
- [How webpack and WordPress packages interact](https://developer.wordpress.org/news/2023/04/how-webpack-and-wordpress-packages-interact/) | Developer Blog
- [Build process diagram](https://excalidraw.com/#json=4aNG9JUti3pMnsfoga35b,ihEAI8p5dwkpjWr6gQmjuw)