vite项目搭建记录v0.0.1

748 阅读1分钟

采用的技术栈

  • 前端框架: react+ts
  • 包管理工具: pnpm
  • css: postcss+less
  • ui库: antd
  • 代码格式化: eslint+prettier

起步

pnpm dlx create-vite

目录结构

image.png

配置文件

vite.config.ts

import { defineConfig } from "vite"; //加入代码提示
import react from "@vitejs/plugin-react";
import path from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()], //react插件
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"), //别名
    },
  },
  css: {
    preprocessorOptions: { //预处理器配置
      //需要pnpm add less -D生效
      less: { 
        javascriptEnabled: true, //配合antd
      },
    },
  },
  server: {
    open: true, //自动打开浏览器
    proxy: { //代理配置
      "/api": {
        target: "https://test.net/api", 
        secure: false,
        changeOrigin: true,
        rewrite: (path) => {
          return path.replace(/^\/api/, "");
        },
      },
    },
  },
});

postcss.config.js

module.exports = {
  plugins: {
    autoprefixer: {}, //根据.browserslistrc自动补全
    cssnano: {},
  },
};

遇到的问题

  • import path from "path"报错,找不到path模块
    原因:typescript默认是没有node模块定义的 解决方案:加入@types/node
  • 找不到预处理文件,less文件配置
    解决方案:css.preprocessorOptions中配置预处理文件配置
  • proxy配置请求不到期望接口
    proxy配置解释:
    1. secure:false,解决http=》https
    2. changeOrigin:修改请求的host,将host修改为target值
    3. target+rewrite:
    fetch('/api/test');
    //无rewrite,实际请求路径https://test.net/api/api/test
    //有rewrite,将/api转化为空字符串,实际请求路径https://test.net/api/test
    
  • postcss.config.js配置问题
//报错:postcss.config.js不支持esmodule的形式
import autoprefixer from "autoprefixer"

image.png

//lint报错:Require statement not part of import statement.eslint[@typescript-eslint/no-var-requires]
const sd = require('autoprefixer')

解决方案

//不引入plugin,postcss.config.js直接引入node_modules已安装的plugin包
module.exports = {
  plugins: {
    autoprefixer: {},
    cssnano: {},
  },
};