阿里云主机折上折
  • 微信号
Current Site:Index > Vue3 project scaffolding

Vue3 project scaffolding

Author:Chuan Chen 阅读数:22109人阅读 分类: Vue.js

The Vue3 project scaffolding is an indispensable tool in modern front-end development, simplifying project initialization, configuration, and build processes. Scaffolding based on Vite or Vue CLI can quickly generate project structures, integrate commonly used technology stacks like TypeScript, Pinia, and Vue Router, and provide out-of-the-box features such as hot module replacement (HMR) and code splitting.

Core Scaffolding Tools Comparison

The two main Vue3 scaffolding solutions currently are:

  1. Vite + Vue: A next-generation build tool with extremely fast startup speeds
  2. Vue CLI: The traditional scaffolding tool with a mature ecosystem

Here are the key differences between the two:

Feature Vite Vue CLI
Build Speed Extremely fast (native ESM) Slower (Webpack)
Configuration Complexity Simple Moderate
Plugin Ecosystem Emerging Mature
HMR Speed Milliseconds Seconds

Creating a Project with Vite

Vite is currently the preferred scaffolding tool for Vue3 projects. The command to create a basic project is:

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

The typical project directory structure includes:

├── public/              # Static assets  
├── src/  
│   ├── assets/          # Module assets  
│   ├── components/      # Shared components  
│   ├── router/          # Routing configuration  
│   ├── stores/          # Pinia state management  
│   ├── views/           # Page components  
│   ├── App.vue          # Root component  
│   └── main.js          # Entry file  
├── vite.config.js       # Vite configuration  
└── package.json  

Example of a Typical Configuration File

Basic vite.config.js configuration:

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

Integrating Common Functional Modules

A complete Vue3 project typically requires integrating the following modules:

Routing Configuration Example

// 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  

State Management Configuration

Using Pinia as the state management library:

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

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

Advanced Scaffolding Customization

For enterprise-level projects, it’s often necessary to extend the basic scaffolding functionality:

Multi-Environment Configuration

// vite.config.js  
export default defineConfig(({ mode }) => {  
  const env = loadEnv(mode, process.cwd())  

  return {  
    define: {  
      __APP_ENV__: JSON.stringify(env.APP_ENV)  
    },  
    // Other configurations...  
  }  
})  

Custom Plugin Development

Creating a simple Vite plugin:

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

Performance Optimization Practices

Automated performance optimization through scaffolding configuration:

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

Enterprise-Level Project Structure Recommendations

For complex projects, a Domain-Driven Design (DDD) structure is recommended:

src/  
├── core/               # Core business logic  
├── modules/            # Functional modules  
│   ├── auth/           # Authentication module  
│   ├── product/        # Product module  
│   └── user/           # User module  
├── shared/             # Shared resources  
│   ├── components/     # Generic components  
│   ├── composables/    # Composable functions  
│   └── utils/          # Utility functions  
└── App.vue  

Extending Automation Scripts

Adding common scripts to 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"  
  }  
}  

Code Standard Integration

Integrating ESLint and Prettier through scaffolding:

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

Test Environment Configuration

Integrating Vitest for unit testing:

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

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

Example test component:

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

Continuous Integration Solution

Configuring automated workflows in 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  

Micro-Frontend Integration Solution

Implementing micro-frontend architecture using qiankun or Module Federation:

// Main app configuration  
import { registerMicroApps, start } from 'qiankun'  

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

start()  

Internationalization Support

Integrating vue-i18n for multilingual support:

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

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

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

export default i18n  

Theme Switching Implementation

Dynamic theming using CSS variables:

<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>  

Component Auto-Import

Optimizing development experience with 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'  
    })  
  ]  
})  

Visual Configuration Tool

For developers unfamiliar with the command line, a graphical tool can be used:

npm install -g @vue/cli  
vue ui  

Mobile Adaptation Solution

Integrating postcss-px-to-viewport for responsive layouts:

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

Server-Side Rendering Configuration

Creating an SSR project with Vite:

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

Basic SSR entry file example:

// 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

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.