方法一

vite.config.js 文件

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';

export default defineConfig({
  plugins: [vue()],
  server: {
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:8000',// 后端接口
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
  resolve: {
    alias: {
        // @ 替代为 src
      '@': resolve(__dirname, 'src'),
       // @component 替代为 src/component
      '@components': resolve(__dirname, 'src/components'),
    },
  },
});

并且 tsconfig.json 文件中

避免 ts 不识别发生报错问题
{
  "compilerOptions": {
    ...
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"],
    },
  },
}

image.png

方法二

数组的形式

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path';

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [{
        // @ 替代为 src
        find: '@',
        replacement: resolve(__dirname, 'src')
      },
      {
        // @component 替代为 src/component
        find: '@components',
        replacement: resolve(__dirname, 'src/components')
      }
    ],
  },
});

并且 tsconfig.json 文件中

避免 ts 不识别发生报错问题
{
  "compilerOptions": {
    ...
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],
      "@components": ["src/components/*"],
    },
  },
}

image.png


Tom_Li
26 声望1 粉丝

热爱学习,热爱总结,热爱广博知识