最近在捣鼓一下vite,因为自己一直在使用react,就选择vite、react来体验一下vite。

使用最简单的方法创建一个应用:​​yarn create vite​​,然后选择react框架。

vite默认配置是使用了defineConfig工具函数:

import { defineConfig } from 'vite'
export default defineConfig({
// ...
})

不管是js还是ts,都可以直接使用defineConfig工具函数,如果需要基于dev、serve或者build命令来选择不同选项,那就选择导出一个函数,比如:

export default defineConfig(({ command, mode, ssrBuild }) => {
if (command === 'serve') {
return {
// dev 独有配置
}
} else {
// command === 'build'
return {
// build 独有配置
}
}
})

共享选项

root

这是项目根目录【index.html的位置】,可以根据自己项目的规范来配置。比如:

const root: string = process.cwd();
export default defineConfig(({ command, mode, ssrBuild }) => {
return {
root,
plugins: [react()]
};
});

base

开发或者生产环境服务的公共基础路径:

vite:常见的配置_字符串

mode

mode就是指明模式,比如:development或者production,如果在vite.config.ts中配置的话,那么就会把serve和build模式下覆盖掉

plugin

应用需用用到的插件,是一个数组,因为应用中可能使用到很多插件。vite+react中插件就是react,比如:

import react from "@vitejs/plugin-react";
const root: string = process.cwd();
export default defineConfig(({ command, mode, ssrBuild }) => {
const { VITE_PUBLIC_PATH, VITE_PORT } = loadEnv(mode, process.cwd(), "");
return {
base: VITE_PUBLIC_PATH,
root,
plugins: [react()]
};
});

resolve.alias

设置别名,比如:完整配置

import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
import { resolve } from "path";

const root: string = process.cwd();

// 查找路径
const pathResolve = (dir: string): string => {
return resolve(__dirname, ".", dir);
};
// 别名
const alias: Record<string, string> = {
"@": pathResolve("src"),
"@build": pathResolve("build"),
};
// https://vitejs.dev/config/
export default defineConfig(({ command, mode, ssrBuild }) => {
const { VITE_PUBLIC_PATH, VITE_PORT } = loadEnv(mode, process.cwd(), "");
return {
base: VITE_PUBLIC_PATH,
root,
plugins: [react()],
resolve: {
alias,
},
};
});

server

开发服务器配置选项。

  1. host,指定开发服务器监听的某个IP地址,如果是设置为​​0.0.0.0​​或者true,那就是默认监听所有的地址。
  2. port,开发服务器端口号
  3. strictPort,设置为true的时候,遇到端口号被占用了,就会直接退出,
  4. https,是否开启HTTPS
  5. open,自动在浏览器中开启应用程序
  6. proxy,请求路径的代理,比如
export default defineConfig({
server: {
proxy: {
// 字符串简写写法:http://localhost:5173/foo -> http://localhost:4567/foo
'/foo': 'http://localhost:4567',
// 带选项写法:http://localhost:5173/api/bar -> http://jsonplaceholder.typicode.com/bar
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
// 正则表达式写法:http://localhost:5173/fallback/ -> http://jsonplaceholder.typicode.com/
'^/fallback/.*': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/fallback/, ''),
},
// 使用 proxy 实例
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
configure: (proxy, options) => {
// proxy 是 'http-proxy' 的实例
}
},
// 代理 websockets 或 socket.io 写法:ws://localhost:5173/socket.io -> ws://localhost:5174/socket.io
'/socket.io': {
target: 'ws://localhost:5174',
ws: true,
},
},
},
})