版本

prefer-template

要求使用模板字面量而不是字符串连接

🔧 可修复

此规则报告的一些问题可以通过 --fix 命令行 选项自动修复

❄️ 已冻结

此规则目前处于冻结状态,不接受功能请求。

在 ES2015 (ES6) 中,我们可以使用模板字面量来代替字符串连接。

const str = "Hello, " + name + "!";
const str = `Hello, ${name}!`;

规则详情

此规则旨在标记使用 + 运算符与字符串的情况。

示例

此规则的错误代码示例

在 Playground 中打开
/*eslint prefer-template: "error"*/

const str = "Hello, " + name + "!";
const str1 = "Time: " + (12 * 60 * 60 * 1000);

此规则的正确代码示例

在 Playground 中打开
/*eslint prefer-template: "error"*/

const str = "Hello World!";
const str1 = `Hello, ${name}!`;
const str2 = `Time: ${12 * 60 * 60 * 1000}`;

// This is reported by `no-useless-concat`.
const str4 = "Hello, " + "World!";

何时不使用它

此规则不应在 ES3/5 环境中使用。

在 ES2015 (ES6) 或更高版本中,如果您不想收到关于字符串连接的通知,您可以安全地禁用此规则。

版本

此规则在 ESLint v1.2.0 中引入。

资源

更改语言