阿里云主机折上折
  • 微信号
您当前的位置:网站首页 > Vue3项目脚手架

Vue3项目脚手架

作者:陈川 阅读数:22110人阅读 分类: Vue.js

Vue3项目脚手架是现代前端开发中不可或缺的工具,它简化了项目初始化、配置和构建流程。基于Vite或Vue CLI的脚手架能快速生成项目结构,集成TypeScript、Pinia、Vue Router等常用技术栈,并提供热更新、代码分割等开箱即用的功能。

脚手架核心工具对比

当前主流的Vue3脚手架方案主要有两种:

  1. Vite + Vue:新一代构建工具,启动速度极快
  2. Vue CLI:传统的脚手架工具,生态完善

以下是两者的主要差异:

特性 Vite Vue CLI
构建速度 极快(ESM原生) 较慢(Webpack)
配置复杂度 简单 中等
插件生态 新兴 成熟
HMR速度 毫秒级 秒级

使用Vite创建项目

Vite是目前Vue3项目的首选脚手架工具。创建基础项目的命令如下:

npm create vite@latest my-vue-app --template vue

项目目录结构通常包含:

├── public/              # 静态资源
├── src/
│   ├── assets/          # 模块资源
│   ├── components/      # 公共组件
│   ├── router/          # 路由配置
│   ├── stores/          # Pinia状态管理
│   ├── views/           # 页面组件
│   ├── App.vue          # 根组件
│   └── main.js          # 入口文件
├── vite.config.js       # Vite配置
└── package.json

典型配置文件示例

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')
    }
  }
})

集成常用功能模块

完整的Vue3项目通常需要集成以下模块:

路由配置示例

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

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

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

export default router

状态管理配置

使用Pinia作为状态管理库:

// src/stores/counter.js
import { defineStore } from 'pinia'

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

高级脚手架定制

对于企业级项目,通常需要扩展基础脚手架功能:

多环境配置

// vite.config.js
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  
  return {
    define: {
      __APP_ENV__: JSON.stringify(env.APP_ENV)
    },
    // 其他配置...
  }
})

自定义插件开发

创建简单的Vite插件:

// plugins/my-plugin.js
export default function myPlugin() {
  return {
    name: 'transform-file',
    transform(code, id) {
      if (id.endsWith('.custom')) {
        return { code: code.replace(/__VERSION__/, '1.0.0') }
      }
    }
  }
}

性能优化实践

通过脚手架配置实现自动化的性能优化:

// vite.config.js
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return 'vendor'
          }
        }
      }
    }
  }
})

企业级项目结构建议

复杂项目推荐采用领域驱动设计(DDD)结构:

src/
├── core/               # 核心业务逻辑
├── modules/            # 功能模块
│   ├── auth/           # 认证模块
│   ├── product/        # 产品模块
│   └── user/           # 用户模块
├── shared/             # 共享资源
│   ├── components/     # 通用组件
│   ├── composables/    # 组合式函数
│   └── utils/          # 工具函数
└── App.vue

自动化脚本扩展

在package.json中添加常用脚本:

{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs",
    "format": "prettier --write .",
    "prepare": "husky install"
  }
}

代码规范集成

通过脚手架集成ESLint和Prettier:

// .eslintrc.js
module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-recommended',
    '@vue/eslint-config-prettier'
  ],
  rules: {
    'vue/multi-word-component-names': 'off'
  }
}

测试环境配置

集成Vitest进行单元测试:

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

export default defineConfig({
  plugins: [vue()],
  test: {
    globals: true,
    environment: 'jsdom'
  }
})

测试组件示例:

// tests/components/Hello.spec.js
import { mount } from '@vue/test-utils'
import HelloWorld from '../../src/components/HelloWorld.vue'

test('displays message', () => {
  const wrapper = mount(HelloWorld, {
    props: {
      msg: 'Hello Vue 3'
    }
  })
  expect(wrapper.text()).toContain('Hello Vue 3')
})

持续集成方案

在GitHub Actions中配置自动化工作流:

# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
      - run: npm ci
      - run: npm run test
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
      - run: npm ci
      - run: npm run build

微前端集成方案

使用qiankun或Module Federation实现微前端架构:

// 主应用配置
import { registerMicroApps, start } from 'qiankun'

registerMicroApps([
  {
    name: 'vue3-subapp',
    entry: '//localhost:7101',
    container: '#subapp-container',
    activeRule: '/vue3'
  }
])

start()

国际化支持

集成vue-i18n实现多语言:

// src/i18n.js
import { createI18n } from 'vue-i18n'

const messages = {
  en: {
    hello: 'Hello!'
  },
  zh: {
    hello: '你好!'
  }
}

const i18n = createI18n({
  locale: 'zh',
  messages
})

export default i18n

主题切换实现

通过CSS变量实现动态主题:

<script setup>
const themes = {
  light: {
    '--primary': '#42b983',
    '--background': '#ffffff'
  },
  dark: {
    '--primary': '#42d392',
    '--background': '#1a1a1a'
  }
}

function setTheme(theme) {
  Object.entries(themes[theme]).forEach(([key, value]) => {
    document.documentElement.style.setProperty(key, value)
  })
}
</script>

<template>
  <button @click="setTheme('light')">Light</button>
  <button @click="setTheme('dark')">Dark</button>
</template>

组件自动导入

使用unplugin-auto-import优化开发体验:

// vite.config.js
import AutoImport from 'unplugin-auto-import/vite'

export default defineConfig({
  plugins: [
    AutoImport({
      imports: [
        'vue',
        'vue-router',
        'pinia'
      ],
      dts: 'src/auto-imports.d.ts'
    })
  ]
})

可视化配置工具

对于不熟悉命令行的开发者,可以使用图形化工具:

npm install -g @vue/cli
vue ui

移动端适配方案

集成postcss-px-to-viewport实现响应式布局:

// postcss.config.js
module.exports = {
  plugins: {
    'postcss-px-to-viewport': {
      viewportWidth: 375,
      unitPrecision: 5
    }
  }
}

服务端渲染配置

使用Vite创建SSR项目:

npm create vite@latest my-ssr-app --template vue-ssr

基础SSR入口文件示例:

// src/entry-server.js
import { createSSRApp } from 'vue'
import App from './App.vue'

export function createApp() {
  const app = createSSRApp(App)
  return { app }
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

前端川

前端川,陈川的代码茶馆🍵,专治各种不服的Bug退散符💻,日常贩卖秃头警告级的开发心得🛠️,附赠一行代码笑十年的摸鱼宝典🐟,偶尔掉落咖啡杯里泡开的像素级浪漫☕。‌