SoFunction
Updated on 2025-03-09

How to use @ to configure path alias in vite

vite uses @ to configure path alias

Report an error

Cannot find module 'XXXXXX ’ or its corresponding type declarations

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
const path = require('path');

export default defineConfig({
  plugins: [vue()],
  define: {
    '': {},
  },
  resolve: {
    //Configure path alias    alias: {
      '@': (__dirname, './src'),
    },
  },
});

Configure baseUrl, paths

{
  "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.", "src/**/*.tsx", "src/**/*.vue"]
}

Use in files

import services from '@/services/index';

vite configuration alias @ and alias input prompts

Configure alias

// 
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

// /config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: [
      {
        find: '@',
        replacement: (__dirname, 'src')
      },
      ...
    ]
  }
})

If path errors, you can install npm i -D @type/node. If it still reports an error, it may be a vite version problem. Change it to import * as path from 'path'

Alias ​​Tips

"compilerOptions": {
    ...
    "baseUrl": "./",
    "paths": {
        "@/*": ["src/*"]
    }
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more.