我正在使用react-intl
并且需要所有使用FormattedMessage
来包含一个description
道具,以便翻译人员获得有关该字符串的一些上下文。我还需要使用eslint
规则强制执行它,以便始终提醒整个团队为每个可翻译字符串提供描述。我该如何设置?
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 还会检测规则并突出显示错误。
有几种方法可以做到这一点。
第一种方法是使用
eslint-plugin-react-intl
. 这个插件会自动将 description 属性添加到它找到的任何 FormattedMessage 实例中。第二种方法是使用
react-intl-enforce-description
ESLint 规则。此规则将检查所有 FormattedMessage 实例是否具有 description 属性,如果没有,则会出错。第三种方式是使用
eslint-plugin-react-intl-display-translations
ESLint 规则。此规则将检查所有 FormattedMessage 实例是否正在用于显示翻译,如果不是,则会出错。此规则对于在仅显示翻译的组件中强制使用 FormattedMessage 实例很有用,如果所有组件都使用 FormattedMessage 实例,则不需要。
您可以使用 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,
};