发布于 1 年前 ,更新于 1 年前 vite,typescript,eslint

使用 Vite + Typescript + ESLint 的项目配置路径别名

使用路径别名可以大大减少项目中 ../../../ 的情况。但配置路径别名则需要分别对 ViteTypeScriptESLint 进行单独的配置。

  • 配置 Vite 可以避免编译出错(如 npm run devnpm run build)。
  • 配置 TypeScript 可以避免 ts 报错( Cannot find module ... )。
  • 配置 ESLint 可以避免 eslint 报错(如果使用了 airbnb 代码风格)
Vite 配置 - vite.config.ts

resolve 属性中配置 alias:

import { defineConfig } from 'vite';
import { resolve } from 'path';

export default defineConfig({
  resolve: {
    alias: {
      '~': resolve(__dirname, './src'),
    },
  },
});
TypeScript 配置 - tsconfig.json

compilerOptions 中添加 paths:

{
  "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
      "~/*": ["./src/*"]
    },  
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"]
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
ESLint 配置 - .eslintrc.js

注意:正常情况下,使用默认的 eslint 配置就可以了,不需要额外的配置。但我这里使用了 eslint 推荐的 airbnb 代码风格,导致需要做一些额外配置。

首先需要安装 eslint-import-resolver-alias 依赖:

npm i eslint-import-resolver-alias -D

eslint 配置文件中添加以下配置:

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'airbnb-base',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 13,
    sourceType: 'module',
  },
  plugins: [
    '@typescript-eslint',
  ],
  settings: {
    'import/resolver': {
      alias: {
        map: [
          ['~', './src'],
        ],
        extensions: ['.ts', '.js', '.jsx', '.tsx'], // 可忽略的后缀名
      },
    },
  },
  rules: {
  },
};

假如 src 目录下有一个 helper.ts 文件,然后在另外一个文件引用该文件:

import helper from '~/helper'

此时 eslint 可能会有如下错误提示:

Missing file extension "ts" for "~/helper" eslint(import/extensions)

如果将代码改成这样:

import helper from '~/helper.ts'

这个时候 eslint 就不再提示错误,但 ts 会提示如下错误:

An import path cannot end with a '.ts' extension. Consider importing '~/helper.js' instead. ts(2691)

所以引用 ts 文件是不能带有后缀,只能去修改 eslint 配置,在 rules 里面添加如下配置即可:

"import/extensions": [
  "error",
  "ignorePackages",
  {
    "js": "never",
    "jsx": "never",
    "ts": "never",
    "tsx": "never"
  }
]
© 2016 - 2023 BY 禾惠 粤ICP备20027042号