title: "功能开关" post_status: publish comment_status: open taxonomy: category: - gutenberg-docs post_tag: - How To Guides - Repos - Data


功能开关

"功能开关"是变量,允许您阻止 Gutenberg 项目中的特定代码发布到 WordPress 核心,并仅在插件中运行某些实验性功能。

介绍 globalThis.IS_GUTENBERG_PLUGIN

globalThis.IS_GUTENBERG_PLUGIN 是一个环境变量,其值用于“标记”代码是否在 Gutenberg 插件内运行。

当代码库为插件构建时,此变量将被设置为 true。当为 WordPress 核心构建时,它将被设置为 falseundefined

Basic usage

Exporting features

A plugin-only function or constant should be exported using the following ternary syntax:

function myPluginOnlyFeature() {
    // implementation
}

export const pluginOnlyFeature = globalThis.IS_GUTENBERG_PLUGIN
    ? myPluginOnlyFeature
    : undefined;

In the above example, the pluginOnlyFeature export will be undefined in non-plugin environments such as WordPress core.

导入功能特性

若需导入并调用仅限插件使用的功能特性,请务必将函数调用包裹在 if 语句中以避免错误:

import { pluginOnlyFeature } from '@wordpress/foo';

if ( globalThis.IS_GUTENBERG_PLUGIN ) {
    pluginOnlyFeature();
}

How it works

During the webpack build, instances of globalThis.IS_GUTENBERG_PLUGIN will be replaced using webpack's define plugin.

For example, in the following code –

if ( globalThis.IS_GUTENBERG_PLUGIN ) {
    pluginOnlyFeature();
}

– the variable globalThis.IS_GUTENBERG_PLUGIN will be replaced with the boolean true during the plugin-only build:

if ( true ) {
    // Webpack has replaced `globalThis.IS_GUTENBERG_PLUGIN` with `true`
    pluginOnlyFeature();
}

This ensures that code within the body of the if statement will always be executed.

In WordPress core, the globalThis.IS_GUTENBERG_PLUGIN variable is replaced with undefined. The built code looks like this:

if ( undefined ) {
    // Webpack has replaced `globalThis.IS_GUTENBERG_PLUGIN` with `undefined`
    pluginOnlyFeature();
}

undefined evaluates to false so the plugin-only feature will not be executed.

死代码消除

对于生产环境构建,webpack 会对代码进行'压缩',尽可能移除不必要的 JavaScript。

其中一个步骤涉及所谓的"死代码消除"。例如,当遇到以下代码时,webpack 会判定周围的 if 语句是不必要的:

if ( true ) {
    pluginOnlyFeature();
}

该条件将始终求值为 true,因此 webpack 会移除它,只保留原函数体内的代码:

pluginOnlyFeature(); // `if` 条件块已被移除,仅保留函数体。

类似地,在为 WordPress 核心构建时,以下 if 语句中的条件始终解析为 false:

if ( undefined ) {
    pluginOnlyFeature();
}

在这种情况下,压缩过程将移除整个 if 语句(包括函数体),确保插件专用代码不会包含在 WordPress 核心构建中。

常见问题

为什么不应将涉及 IS_GUTENBERG_PLUGIN 的表达式结果赋值给变量,例如 const isMyFeatureActive = ! Object.is( undefined, globalThis.IS_GUTENBERG_PLUGIN )

引入复杂性可能会阻止 webpack 的压缩工具识别并因此消除死代码。因此,建议使用本文档中的示例,以确保您的功能标志按预期工作。更多详细信息,请参阅死代码消除部分。