我正在使用 react-intl
并且需要 FormattedMessage
的所有用途包含 description
prop 以便翻译人员获得有关该字符串的一些上下文。我还需要使用 eslint
强制执行它规则,因此始终提醒整个团队为每个可翻译字符串提供描述。我该如何设置?
最佳答案
您可以按照这些文章创建自定义规则:
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,您可以按照此 guide
Here您可以看到该规则有效。只需克隆它并移至
custom-eslint-formatted-message
目录,然后运行 npm i
npm run lint
. vscode 还会检测规则并突出显示错误。关于javascript - 如何使用 eslint 在 FormattedMessage 组件中强制描述属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69758272/