install vite
npm install -g vite
npm list -g vite
npm update -g vite
create project
npm create vite@latest my-vue-app
project setup
cd my-vue-app
npm install
hot-reloads for development
npm run dev
compiles and minifies for production
npm run build
preview
npm run preview
common configurations
vite.config.ts
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from "path";
const root: string = process.cwd();
const regExps = (value: string, reg: string): string => {
return value.replace(new RegExp(`^${reg}`, "g"), "");
};
const pathResolve = (dir: string): string => {
return resolve(__dirname, ".", dir);
};
const alias: Record<string, string> = {
"/@": pathResolve("src"),
"@build": pathResolve("build")
};
export default defineConfig(({ command, mode }) => {
const env = loadEnv(mode, root + '/env', '');
return {
base: env.VITE_PUBLIC_PATH,
plugins: [vue()],
resolve: { alias }, // 设置别名
server: {https: false, // 是否开启 https
host: "0.0.0.0", // 监听来自所有ip的请求
port: env.VITE_PORT, // 端口号
proxy: {[env.VITE_PROXY_DOMAIN]: {target: env.VITE_PROXY_DOMAIN_REAL,
// ws: true,
changeOrigin: true,
rewrite: (path: string) => regExps(path, env.VITE_PROXY_DOMAIN)} // VITE_PROXY_DOMAIN 代理
} // 所有代理
} // 服务器配置
} // return change config
});
env
env/.env
VITE_PORT = 8080 # 项目本地运行端口号
VITE_ROUTER_HISTORY = "hash" # 开发环境路由历史模式
VITE_PROXY_DOMAIN = /api # 开发环境代理
VITE_PROXY_DOMAIN_REAL = "http://127.0.0.1:8081" # 开发环境后端地址
packge depend
package.json
{
"name": "my-vue-app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {"dev": "vite",
"build": "vue-tsc && vite build",
"preview": "vite preview"
},
"dependencies": {"vue": "^3.3.4"},
"devDependencies": {"@vitejs/plugin-vue": "^4.2.3",
"typescript": "^5.0.2",
"vite": "^4.4.5",
"vue-tsc": "^1.8.5"
}
}