vite+vue3项目创建教程

Gary Chen
vite+vue3项目创建教程

1. 环境准备

首先确保你的系统已安装:

  • Node.js (建议版本 16.x 或更高)
  • npm 或 yarn (推荐使用 pnpm)

2. 创建项目

方法一:使用 Vite 官方脚手架

# 使用 npm
npm create vite@latest my-vue-app --template vue

# 使用 yarn
yarn create vite my-vue-app --template vue

# 使用 pnpm
pnpm create vite my-vue-app --template vue

方法二:手动选择配置

npm create vite@latest

然后按提示操作:

  1. 输入项目名称
  2. 选择框架:Vue
  3. 选择变体:JavaScript 或 TypeScript

3. 项目结构说明

创建后的项目结构如下:

my-vue-app/
├── node_modules/      # 依赖包
├── public/            # 静态资源
├── src/               # 源代码
│   ├── assets/        # 静态资源
│   ├── components/    # 组件
│   ├── App.vue        # 根组件
│   └── main.js        # 入口文件
├── index.html         # 主页面
├── package.json       # 项目配置
├── vite.config.js     # Vite 配置
└── README.md          # 项目说明

4. 安装依赖并运行

# 进入项目目录
cd my-vue-app

# 安装依赖
npm install  # 或 yarn 或 pnpm install

# 启动开发服务器
npm run dev

启动后访问 http://localhost:5173 即可看到默认页面。

5. 常用配置

修改 vite.config.js

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

export default defineConfig({
  plugins: [vue()],
  server: {
    port: 3000, // 自定义端口
    open: true // 自动打开浏览器
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src') // 设置路径别名
    }
  }
})

配置路径别名

  1. 安装 path 依赖:
npm install path --save-dev
  1. 修改 vite.config.js:
import path from 'path'

export default defineConfig({
  // ...其他配置
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  }
})

6. 添加常用依赖

安装 Vue Router

npm install vue-router@4

创建路由配置文件 src/router/index.js

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

main.js 中使用路由:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)
app.mount('#app')

安装 Pinia (状态管理)

npm install pinia

创建 store src/stores/counter.js

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count++
    }
  }
})

main.js 中使用:

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const app = createApp(App)
app.use(createPinia())
app.mount('#app')

7. 项目构建

# 开发模式
npm run dev

# 生产构建
npm run build

# 预览生产构建
npm run preview

8. 添加 ESLint + Prettier

安装依赖

npm install eslint eslint-plugin-vue @typescript-eslint/parser @typescript-eslint/eslint-plugin prettier eslint-config-prettier eslint-plugin-prettier -D

配置 .eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/typescript/recommended',
    'plugin:prettier/recommended',
  ],
  parserOptions: {
    ecmaVersion: 2020,
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'prettier/prettier': 'warn',
  },
}

配置 .prettierrc

{
  "semi": false,
  "singleQuote": true,
  "printWidth": 80,
  "trailingComma": "es5",
  "tabWidth": 2
}

9. 添加 CSS 预处理器

安装 Sass

npm install sass -D

然后在组件中可以直接使用:

<style lang="scss">
$primary-color: #42b983;

.text {
  color: $primary-color;
}
</style>

10. 环境变量配置

创建 .env.development.env.production 文件:

# .env.development
VITE_API_BASE_URL=http://localhost:3000/api
# .env.production
VITE_API_BASE_URL=https://api.example.com

在代码中使用:

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL

11. 部署项目

静态站点部署

  1. 构建项目:
npm run build
  1. dist 目录上传到你的静态网站托管服务(如 Vercel、Netlify、GitHub Pages 等)

Docker 部署

创建 Dockerfile

# 构建阶段
FROM node:16 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# 生产阶段
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

构建并运行:

docker build -t my-vue-app .
docker run -d -p 8080:80 my-vue-app

现在你已经完成了一个完整的 Vite + Vue 3 项目的创建和基本配置!