块编辑器开发文档

@wordpress/warning

💡 云策文档标注

概述

@wordpress/warning 是一个用于在控制台输出警告消息的实用工具,基于传入的条件进行判断。它主要用于开发环境,帮助开发者调试和识别潜在问题。

关键要点

  • 安装方式:通过 npm install @wordpress/warning --save 安装,要求运行环境支持 ES2015+,否则需包含 @wordpress/babel-preset-default 中的 polyfill。
  • 减少包大小:警告消息中的字面字符串不会压缩,可能增加生产包大小。建议使用 @wordpress/warning/babel-plugin 或 @wordpress/babel-preset-default 包装警告调用,并配合 UglifyJS、Terser 等工具进行死代码消除。
  • API 使用:默认导出 warning 函数,在非生产环境下显示警告消息。参数为字符串 message,表示要显示的警告内容。
  • 贡献方式:此包是 Gutenberg 项目的一部分,采用 monorepo 结构。贡献者需参考项目的主要贡献指南。

代码示例

import warning from '@wordpress/warning';

function MyComponent( props ) {
  if ( ! props.title ) {
    warning( '`props.title` was not passed' );
  }
  ...
}

注意事项

  • 警告调用在生产模式下会被移除,确保通过 babel 插件和代码压缩工具配置以避免包大小问题。
  • 此包专为 WordPress 和 Gutenberg 项目设计,但也可用于其他 JavaScript 项目。

📄 原文内容

Utility for warning messages to the console based on a passed condition.

Installation

Install the module

npm install @wordpress/warning --save

This package assumes that your code will run in an ES2015+ environment. If you’re using an environment that has limited or no support for such language features and APIs, you should include the polyfill shipped in @wordpress/babel-preset-default in your code.

Reducing bundle size

Literal strings aren’t minified. Keeping them in your production bundle may increase the bundle size significantly.

To prevent that, you should:

  1. Put @wordpress/warning/babel-plugin into your babel config or use @wordpress/babel-preset-default, which already includes the babel plugin.

    This will make sure your warning calls are wrapped within a condition that checks if SCRIPT_DEBUG === true.

  2. Use UglifyJS, Terser or any other JavaScript parser that performs dead code elimination. This is usually used in conjunction with JavaScript bundlers, such as webpack.

    When parsing the code in production mode, the warning call will be removed altogether.

API

default

Shows a warning with message if environment is not production.

Usage

import warning from '@wordpress/warning';

function MyComponent( props ) {
  if ( ! props.title ) {
    warning( '`props.title` was not passed' );
  }
  ...
}

Parameters

  • message string: Message to show in the warning.

Contributing to this package

This is an individual package that’s part of the Gutenberg project. The project is organized as a monorepo. It’s made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to npm and used by WordPress as well as other software projects.

To find out more about contributing to this package or Gutenberg as a whole, please read the project’s main contributor guide.