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

Vue模板标签间空格换行未忽略,如何通过webpack或lint去除多余空格

Vue 模板多余空格去除配置方案

1. 修复 vue.config.js 中的webpack配置

你现有配置不生效的核心原因是tap回调没有返回修改后的options,修改后配置如下,需根据你的Vue版本选择:

Vue 2 项目配置

chainWebpack: (config) => {
  config.module
    .rule('vue')
    .use('vue-loader')
    .tap(options => {
      // condense模式会删除标签头尾的空白字符,连续空白合并为单个空格
      options.compilerOptions.whitespace = "condense"
      options.optimizeSSR = false
      // 必须返回修改后的配置,否则修改不生效
      return options
    })
}

Vue 3 项目配置

Vue 3 默认whitespace已经是condense,如果仍有多余空格可以显式指定:

chainWebpack: (config) => {
  config.module
    .rule('vue')
    .use('vue-loader')
    .tap(options => {
      options.compilerOptions = {
        ...(options.compilerOptions || {}),
        whitespace: 'condense'
      }
      return options
    })
}

配置修改后请删除node_modules/.cache目录清除缓存后再重启服务,避免旧缓存导致配置不生效。

2. ESLint 校验规则配置

安装eslint-plugin-vue后,在.eslintrc.js中添加以下规则,从编码阶段规避多余换行空格问题:

module.exports = {
  rules: {
    // 禁止出现不规范的空白字符
    'vue/no-irregular-whitespace': 'error',
    // 关闭单行元素内容强制换行规则,避免引入首尾空格
    'vue/singleline-html-element-content-newline': 'off',
    // 多行元素内容强制换行对齐,避免不必要的内联空白
    'vue/multiline-html-element-content-newline': 'error'
  }
}

3. Prettier 配套配置(如果项目使用Prettier)

如果项目接入了Prettier做代码格式化,需要在.prettierrc中添加以下配置,避免格式化自动引入多余空格:

{
  "htmlWhitespaceSensitivity": "css",
  "singleAttributePerLine": false
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:27:01