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

如何创建同时兼容Vue 2与Vue 3的可复用ESLint配置?

实现兼容Vue 2/3的可复用ESLint配置包

不用vue-demi,直接在ESLint配置文件里动态检测项目的Vue版本、加载对应规则即可,具体实现步骤如下:

1. 初始化NPM包结构

创建一个新的NPM包(比如命名为eslint-config-vue-cross),核心文件结构如下:

eslint-config-vue-cross/
├── index.js          # 主配置入口
├── vue2.config.js    # Vue 2专属配置片段
├── vue3.config.js    # Vue 3专属配置片段
└── package.json

2. 编写版本检测逻辑

在index.js中,读取项目根目录的Vue包版本,判断加载对应版本的配置:

// 检测项目中安装的Vue主版本
function getVueMajorVersion() {
  try {
    // 从项目根目录解析Vue的package.json,避免读取包自身的依赖
    const vuePackagePath = require.resolve('vue/package.json', {
      paths: [process.cwd()]
    });
    const vuePackage = require(vuePackagePath);
    return parseInt(vuePackage.version.split('.')[0], 10);
  } catch (err) {
    throw new Error('未在项目中检测到Vue,请先安装Vue');
  }
}

// 加载对应版本的配置
const vueVersion = getVueMajorVersion();
const versionSpecificConfig = vueVersion === 2 
  ? require('./vue2.config.js') 
  : require('./vue3.config.js');

// 基础通用配置(环境、全局变量等)
const baseConfig = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  }
};

// 合并并导出最终配置
module.exports = {
  ...baseConfig,
  ...versionSpecificConfig
};

3. 编写Vue 2/3专属配置

  • vue2.config.js(适配eslint-plugin-vue的Vue 2规则集):
module.exports = {
  extends: [
    'plugin:vue/essential',
    'plugin:vue/strongly-recommended',
    'plugin:vue/recommended'
  ],
  parser: 'vue-eslint-parser',
  rules: {
    // Vue 2专属规则示例
    'vue/no-deprecated-slot-attribute': 'error'
  }
};
  • vue3.config.js(适配eslint-plugin-vue的Vue 3规则集):
module.exports = {
  extends: [
    'plugin:vue/vue3-essential',
    'plugin:vue/vue3-strongly-recommended',
    'plugin:vue/vue3-recommended'
  ],
  parser: 'vue-eslint-parser',
  rules: {
    // Vue 3专属规则示例
    'vue/no-deprecated-v-is': 'error'
  }
};

4. 配置package.json

确保包的依赖声明正确,让用户安装时自动匹配所需依赖:

{
  "name": "eslint-config-vue-cross",
  "version": "1.0.0",
  "main": "index.js",
  "peerDependencies": {
    "eslint": "^7.0.0 || ^8.0.0",
    "eslint-plugin-vue": "^7.0.0 || ^8.0.0",
    "vue": "^2.0.0 || ^3.0.0"
  },
  "keywords": ["eslint", "eslint-config", "vue2", "vue3"]
}

5. 项目中使用

在需要复用配置的项目里,先安装这个包:

npm install eslint-config-vue-cross --save-dev

然后在项目的.eslintrc.js中引用:

module.exports = {
  extends: ['vue-cross']
};

注意事项

  • 确保用户项目中已安装对应版本的eslint和eslint-plugin-vue(peerDependencies会自动提示缺失)
  • 若需扩展自定义规则,可在baseConfig或版本专属配置中添加
  • 测试时需分别在Vue 2和Vue 3项目中验证配置是否生效

内容的提问来源于stack exchange,提问作者Kris D. J.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:57:28