天天看点

解决eslint与webstorm/hbuildx等关于script标签的缩进问题

问题重现

在vue-cli中,使用eslint时会对代码进行校验,其在.vue文件中支持的是不缩进,如下所示:

<script>
import HelloWorld from './components/HelloWorld'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>
           

而在webstorm/hbuildx中使用格式化代码会将代码格式化有缩进的,如下所示:

<script>
  import HelloWorld from './components/HelloWorld'

  export default {
    name: 'App',
    components: {
      HelloWorld
    }
  }
</script>
           

解决方案

修改ESLint的配置

打开项目根下的.eslintrc.js文件,将rules节点添加如下配置项:

rules: {
  'vue/script-indent': ['error', 2, {'baseIndent': 1}]
}
           

其中,数字2表示统一缩进2个空格,数字1表示1倍缩进

此外,还需要添加以下内容:

overrides:[
	{
		'files':['*.vue'],
		'rules':{
			'indent':'off'
		}
	}
]
           

全部内容如下:

rules: {
    // allow async-await
    'generator-star-spacing': 'off',
    // allow debugger during development
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    rules: {
      'vue/script-indent': ['error', 2, {'baseIndent': 1}]
    }
  },
  overrides:[
  	{
  		'files':['*.vue'],
  		'rules':{
  			'indent':'off'
  		}
  	}
  ]
           

参考文章: https://blog.csdn.net/tozeroblog/article/details/85346166