关闭ESlint/路径起别名/配置前端代理/引入模块报错

发布时间 2023-08-12 09:52:17作者: dimiaslong

怎么关闭ESlint语法检查(不建议)

  1. vue-cli创建的项目, 在vue.config.js​文件里面
// vue.config.js
const { defineConfig } = require('@vue/cli-service');
module.exports = defineConfig({
  lintOnSave: false,
})
  1. vite创建的项目, 在vite.config.js​文件里面
import { defineConfig } from 'vite';
export default defineConfig({
   lintOnSave: false,  
})

怎么给路径起别名和代码提示

  1. vue-cli创建的项目, 在jsconfig.json​文件里面
{
  "compilerOptions": {
    "baseUrl": "./",
      "paths": {
        "@/*":[
          "src/*"
        ]
      },
  }
}
  1. vite创建的项目, 在vite.config.js​​文件里面
import { defineConfig } from 'vite';
import path from 'path';
export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
})

如果是vite.config.ts​文件,还需要先安装npm i @types/node -D​,并且在tsconfig.node.json​配置

"compilerOptions": {
	...
    "allowSyntheticDefaultImports": true
  },

要想有别名的提示, 还需要在tsconfig.json​或者jsconfig.json​里面

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

怎么配置前端代理服务器

  1. vue.config.js​​里面
const { defineConfig } = require('@vue/cli-service'); 
module.exports = defineConfig({
  devServer: {
    proxy: {
      api: {
        target: 'http://sph-h5-api.atguigu.cn/',
        changeOrigin: true,
        pathRewrite: { '^/api': '' },
      },
    },
  },
});
  1. 或者是在vite.config.js​里面
import { defineConfig } from 'vite'
export default defineConfig({
  server:{
    proxy:{
      '/api': {
        target: 'http://ceshi13.dishait.cn',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      },
    }
  }
})

  1. 引入axios实例, 配置请求和响应拦截器(一般在src文件夹下面的utils文件夹里面)
import axios from 'axios';
import nProgress from 'nprogress';
import 'nprogress/nprogress.css';

// 创建axios实例
const request = axios.create({
  // 发送请求到目标服务器前会将baseURL自动拼接到请求路径前面
  baseURL: '/api',
  // 每条并发的最大等待时间,时间到了返回404
  timeout: 10000,
});

// 创建请求拦截器
// 会在axios请求发送之前拦截
request.interceptors.request.use((config) => {
  nProgress.start();  
  // 添加请求头的信息
  config.headers.aaa = 123;
  // 一定要写return config
  return config;
});

// 创建响应拦截器
// 会在响应返回到浏览器之后触发
// 第一个回调是请求成功的回调
// 第二个回调是请求失败的回调
request.interceptors.response.use(
  (response) => {
    //  根据状态码不同的处理
    if (response.data.code === 200) {
      nProgress.done();
      return response.data;
    }  else {
      nProgress.done();
      return Promise.reject(response.data.message);
    }
  },
  () => {
    nProgress.done();
    return Promise.reject('请求失败');
  }
);
export default request;

引入模块报错

奇怪的错误:
Cannot find module 'vue'. Did you mean to set the 'moduleResolution' option tonodenext',or to add aliases to the 'paths' option? ts(2792)

离谱, 连vue模块都没有了, 解决方法:

在​tsconfig.json​或者jsconfig.json​里面

{
  "compilerOptions": {
+   "moduleResolution": "node"
  }
}