WordPress 的弃用工具。记录一条消息,通知开发人员有关已弃用的功能。

安装

安装模块

npm install @wordpress/deprecated --save

此包假设您的代码将在ES2015+环境中运行。如果您使用的环境对这些语言特性和 API 的支持有限或完全不支持,则应在代码中包含@wordpress/babel-preset-default随附的多填充(polyfill)。

钩子

deprecated操作会触发三个参数:已弃用功能的名称、传递给 deprecated 的选项对象以及发送到控制台的消息。

示例:

import { addAction } from '@wordpress/hooks';

function addDeprecationAlert( message, { version } ) {
    alert( `Deprecation: ${ message }. Version: ${ version }` );
}

addAction(
    'deprecated',
    'my-plugin/add-deprecation-alert',
    addDeprecationAlert
);

API

default

记录一条消息,通知开发人员有关已弃用的功能。

用法

import deprecated from '@wordpress/deprecated';

deprecated( 'Eating meat', {
    since: '2019.01.01',
    version: '2020.01.01',
    alternative: 'vegetables',
    plugin: 'the earth',
    hint: 'You may find it beneficial to transition gradually.',
} );

// Logs: 'Eating meat is deprecated since version 2019.01.01 and will be removed from the earth in version 2020.01.01. Please use vegetables instead. Note: You may find it beneficial to transition gradually.'

参数

  • feature string:已弃用功能的名称。
  • options [DeprecatedOptions]:个性化选项

logged

用于跟踪已记录消息的对象映射,以确保每条消息仅记录一次。

类型

  • Record< string, true >

单元测试弃用项

每个弃用消息在加载此包的实例期间仅记录一次。导出的 logged 对象会跟踪完整的消息文本。重置控制台间谍(spy)不会清除此状态。

Gutenberg 的内部 Vitest 设置在 Node、jsdom 和 Browser Mode 下的每个测试之前都会清除 logged。套件无需进行自己的弃用历史记录清理。如果每个触发弃用的测试都断言了警告,则无需与 logged 交互。消息在测试内仍只记录一次。请参阅预期的控制台调用。

对于练习弃用功能的套件,请在 beforeEach 中标记其消息为已记录,以在其他行为的测试期间抑制它。在测试警告本身之前删除该条目。

以下示例使用 Vitest 和 Gutenberg 测试设置提供的 toHaveWarnedWith 匹配器:

import { beforeEach, describe, expect, it } from 'vitest';
import deprecated, { logged } from '@wordpress/deprecated';

const DEPRECATION_MESSAGE = 'legacyFeature is deprecated.';

describe( 'legacyFeature', () => {
    beforeEach( () => {
        logged[ DEPRECATION_MESSAGE ] = true;
    } );

    it( 'warns that the feature is deprecated', () => {
        delete logged[ DEPRECATION_MESSAGE ];
        deprecated( 'legacyFeature' );

        expect( console ).toHaveWarnedWith( DEPRECATION_MESSAGE );
    } );
} );

设置 logged 条目还会阻止 deprecated 操作触发。在测试该操作时,请保持该条目不存在。

如果您的测试设置不清除 logged,前面的测试可能会阻止后面的测试观察到相同的警告。在 beforeEach 和 afterEach 中删除套件使用的消息条目,以保持测试独立性。对于抑制警告的测试,请在 beforeEach 中设置其条目而不是删除它。将清理工作限制为套件使用的消息。

为此包做出贡献

这是 Gutenberg 项目的一部分独立包。该项目组织为单体仓库(monorepo)。它由多个自包含的软件包组成,每个包都有特定的用途。此单体仓库中的包发布到 npm,并被 WordPress 以及其他软件项目使用。

要了解有关为此包或整个 Gutenberg 做出贡献的更多信息,请阅读项目的主要贡献者指南。