如何使用 linter 在 vue 中强制执行脚本、模板和样式标签的顺序

How to enforce script, template and style tags order in vue with linter

我想添加一个检查标签是否按以下顺序排列的 linter 规则:<script><template><style>。 Vue 的默认是 <template> 第一,但我想要 <script> 因为我认为它更重要。

如果这可以自动修复那就太棒了。

我找不到这个 eslint 规则,如果没有我可能会考虑创建它。

eslint-plugin-vue 为此支持 component-tags-order rule。它已经包含在 "plugin:vue/vue3-recommended""plugin:vue/recommended" 规则集中(如果使用 Vue CLI 脚手架项目)。

执行 <script><template><style> 的配置:

// .eslintrc.js
module.exports = {
  rules: {
    'vue/component-tags-order': ['error', {
      order: [ 'script', 'template', 'style' ]
    }],
  }
}

请注意,该规则不会实现自动修复,因此您只会遇到 linter 错误。

但是,有一个命令行实用程序 (v-change-tags-order),您可以 运行 重新排列标签:

npx v-change-tags-order