You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Linter移除Angular双花括号中的空格?

移除Angular模板插值语法{{}}内的首尾空格(lint检查+自动格式化)

现有工具的局限

Prettier仅支持给插值语法添加首尾空格(比如把{{foo}}改成{{ foo }}),相关反向需求的缺陷已关闭,官方不会支持移除空格的配置;ESLint及@angular-eslint插件也没有现成规则覆盖这个场景,加上Angular官方文档在空格使用上的不一致,只能通过自定义方案来统一项目风格。

解决方案

1. 自定义ESLint规则(支持lint检查+自动修复)

利用@angular-eslint的模板解析能力,编写自定义规则来检测并修复插值语法的首尾空格:

步骤1:创建自定义规则文件

在项目根目录新建eslint-rules/no-interpolation-spaces.js,内容如下:

module.exports = {
  create(context) {
    return {
      // 监听Angular模板中的插值节点
      Interpolation(node) {
        const rawContent = context.getSourceCode().getText(node);
        // 匹配{{后、}}前的首尾空格并移除
        const fixedContent = rawContent.replace(/{{\s*(.*?)\s*}}/g, '{{$1}}');
        if (fixedContent !== rawContent) {
          context.report({
            node,
            message: '插值语法{{}}内禁止首尾空格',
            fix(fixer) {
              return fixer.replaceText(node, fixedContent);
            }
          });
        }
      }
    };
  }
};

步骤2:配置ESLint

在项目的.eslintrc.json中添加自定义规则的配置:

{
  "plugins": [
    // 注册自定义规则插件,指向规则所在目录
    "custom": {
      "rules": {
        "no-interpolation-spaces": "./eslint-rules/no-interpolation-spaces.js"
      }
    }
  ],
  "overrides": [
    {
      "files": ["*.html"],
      "parser": "@angular-eslint/template-parser",
      "rules": {
        "custom/no-interpolation-spaces": "error"
      }
    }
  ]
}

步骤3:运行检查与修复

执行以下命令完成lint检查和自动修复:

ng lint --fix

2. 批量脚本处理(快速统一现有代码)

如果需要一次性修复项目中所有模板文件的插值空格,可以写一个Node.js脚本批量处理:

在项目根目录新建fix-interpolation-spaces.js,内容如下:

const fs = require('fs');
const path = require('path');

// 处理单个HTML文件
function fixFile(filePath) {
  const content = fs.readFileSync(filePath, 'utf8');
  // 替换插值语法的首尾空格
  const updatedContent = content.replace(/{{\s*(.*?)\s*}}/g, '{{$1}}');
  if (updatedContent !== content) {
    fs.writeFileSync(filePath, updatedContent, 'utf8');
    console.log(`已修复:${filePath}`);
  }
}

// 遍历目录下所有HTML文件
function traverseDir(dir) {
  const files = fs.readdirSync(dir);
  files.forEach(file => {
    const fullPath = path.join(dir, file);
    const stat = fs.statSync(fullPath);
    if (stat.isDirectory()) {
      traverseDir(fullPath);
    } else if (fullPath.endsWith('.html')) {
      fixFile(fullPath);
    }
  });
}

// 执行脚本,替换为你的项目源码目录(默认是src)
traverseDir('./src');

执行脚本:

node fix-interpolation-spaces.js

注意事项

  • 正则表达式/{{\s*(.*?)\s*}}/g采用非贪婪匹配,能兼容带管道(Pipe)的插值语法,比如{{ foo | uppercase }}会被修复为{{foo|uppercase}};如果需要保留管道前后的空格,可以调整正则为/{{\s*([^}\s].*?[^}\s])\s*}}/g(仅移除{{后和}}前的首尾空格,保留中间内容的空格)。
  • 自定义ESLint规则需要维护,当@angular-eslint版本升级时,可能需要适配模板解析器的API变化。
  • 批量脚本执行前建议先提交代码,避免意外修改无法回滚。

内容的提问来源于stack exchange,提问作者R3gi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 19:30:56