4

我正在使用react-intl并且需要所有使用FormattedMessage来包含一个description道具,以便翻译人员获得有关该字符串的一些上下文。我还需要使用eslint规则强制执行它,以便始终提醒整个团队为每个可翻译字符串提供描述。我该如何设置?

4

3 回答 3

3

您可以按照这些文章创建自定义规则:

https://blog.scottlogic.com/2021/09/06/how-to-write-an-es-lint-rule-for-beginners.html https://flexport.engineering/writing-custom-lint-rules -for-your-picky-developers-67732afa1803

我写了一个规则来description在一个名为的组件上强制执行道具FormattedMessage

const ERROR_DESCRIPTION_MISSING =
  "FormattedMessage component should have a `description` prop";

module.exports = {
  meta: {
    type: "problem",
    schema: [],
  },
  create: (context) => {
    return {
      JSXOpeningElement: function (node) {
        const nodeType = node.name.name;
        if (nodeType !== "FormattedMessage") {
          return;
        }
        if (!node.attributes.find((attr) => attr.name.name === "description")) {
          context.report({
            node: node,
            message: ERROR_DESCRIPTION_MISSING,
          });
        }
      },
    };
  },
};

此规则将适用于任何名为FormattedMessage. 我不确定是否可以识别它来自哪里的导入以检查它是一个react-intl组件。

创建自定义 eslint 插件后,您需要将此新规则添加到您的项目中。这将取决于您的项目设置,但如果您使用 CRA,则可以遵循本指南

在这里你可以看到规则的工作。只需克隆它并移动到custom-eslint-formatted-message目录,然后运行npm i npm run lint​​. vscode 还会检测规则并突出显示错误。 在此处输入图像描述

于 2021-11-26T04:44:31.537 回答
2

有几种方法可以做到这一点。

  • 第一种方法是使用eslint-plugin-react-intl. 这个插件会自动将 description 属性添加到它找到的任何 FormattedMessage 实例中。

  • 第二种方法是使用react-intl-enforce-descriptionESLint 规则。此规则将检查所有 FormattedMessage 实例是否具有 description 属性,如果没有,则会出错。

  • 第三种方式是使用eslint-plugin-react-intl-display-translationsESLint 规则。此规则将检查所有 FormattedMessage 实例是否正在用于显示翻译,如果不是,则会出错。此规则对于在仅显示翻译的组件中强制使用 FormattedMessage 实例很有用,如果所有组件都使用 FormattedMessage 实例,则不需要。

于 2021-12-01T09:03:17.807 回答
0

您可以使用 PropTypes。它早期是 React 的一部分,但现在它有自己的 npm 包, https: //www.npmjs.com/package/prop-types 。如果没有提供道具,这会给你一个运行时错误。它也很有用,因为如果你错过它们,linter 可以警告你。 https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md

import React from 'react';
import PropTypes from 'prop-types'; 

const MyComponent = (props) => (
  <div className={props.name}>
    {props.description}
  </div>
);

MyComponent.propTypes = {
  name: PropTypes.string.isRequired,
  description: PropTypes.string.isRequired,
};
于 2021-10-28T17:23:09.607 回答