使用 Vue 官方脚手架初始化 Vue3 项目

Vite 官网:https://cn.vitejs.dev/

Vue 官网:https://vuejs.org/

Vue 官方文档:https://cn.vuejs.org/guide/introduction.html

Element Plus 官网:https://element-plus.org/

Tailwind CSS 官网:https://tailwindcss.com/

Tailwind CSS 中文文档 (73zls.com):https://tailwind.docs.73zls.com/docs/responsive-design
NPM 官网:https://www.npmjs.com/
Vite 官方中文文档:https://cn.vitejs.dev/

安装 Node 环境

首先,确保已经安装了 Node.js,可以在命令行中运行 node -vnpm -v 来检查它们是否已经正确安装:

image-20231210121140490

安装 Node.js 通常会自动附带安装 npm,所以你不需要单独安装 npm。只需确保 Node.js 版本符合要求即可。

切换 NPM 镜像源

使用 nrm 来管理 npm 镜像源可以帮助加速 npm 包的下载速度。

  1. 执行命令通过 npm 全局安装 nrm

    npm install -g nrm
    
  2. 使用 nrm ls 命令列出当前可用的镜像源,以及它们的地址和当前使用的镜像源:

    nrm ls
    
  3. 使用 nrm use 命令来切换想要使用的镜像源,例如,切换到淘宝镜像源:

    nrm use taobao
    
  4. 使用以下命令来验证切换是否成功:

    npm config get registry
    

安装 Pnpm 包管理工具

  1. 在命令行中执行以下命令全局安装 pnpm:

    npm install -g pnpm
    
  2. 安装完成后,可以使用 pnpm 来代替 npm 进行包管理。例如,使用以下命令来安装项目依赖:

    pnpm install
    

    这将使用 pnpm 来安装项目所需的包,而不是使用默认的 npm。

使用 Vue 官方脚手架初始化项目

  1. 切换到打算创建项目的目录,输入 cmd 打开命令行,之后在命令行中运行以下命令:

    pnpm create vue@latest
    
  2. 运行命令后使用方向键和回车键选择【否/是】开启或关闭某个功能:

    test

  3. 创建完项目之后,在命令行中继续输入以下命令运行项目:

    cd <your-project-name>
    pnpm i
    pnpm run dev --open
    

    test-1

认识 Vue 项目目录结构

Vue 3 项目的典型目录结构如下:

project-name/
├── public/                # 静态资源目录
│   └── favicon.ico        # 网站图标
├── src/                   # 源代码目录
│   ├── assets/            # 资源文件目录(图片、样式等)
│   ├── components/        # 组件目录
│   │   └── HelloWorld.vue # 示例组件
│   ├── router/            # 路由配置目录
│   │   └── index.ts       # 路由配置文件
│   ├── store/             # 状态管理目录
│   │   └── index.ts       # 状态管理配置文件(Pinia)
│   ├── views/             # 视图目录
│   │   └── Home.vue       # 示例视图组件
│   ├── App.vue            # 根组件
│   └── main.ts            # 项目入口文件(使用 TypeScript)
├── .eslintrc.js           # ESLint 配置文件
├── .gitignore             # Git 忽略文件配置
├── .prettierrc.json       # Prettier 配置文件
├── env.d.ts       		   # 声明文件,用于声明全局环境变量的类型
├── index.html       	   # 入口 HTML 文件
├── package.json           # 项目配置文件
├── README.md              # 项目说明文件
├── tsconfig.json          # TypeScript 配置文件
└── vite.config.js         # Vite 配置文件

统一包管理器工具下载依赖

  1. 创建scripts\preinstall.js文件,添加:

    if (!/pnpm/.test(process.env.npm_execpath || '')) {
      console.warn(
        `\u001b[33mThis repository must using pnpm as the package manager` +
          `for scripts to work properly.\u001b[39m\n`
      )
      process.exit(1)
    }
    
  2. 在 package.json 中配置命令:

    "scripts": {
        "preinstall":"node ./scripts/preinstall.js"
    }
    

    preinstall是 npm 提供的生命周期钩子,当我们使用 yarn 或 npm 来安装依赖的时候就会触发 preinstall

项目环境变量配置

没有基础的同学可以先去阅读下环境变量的文章:认识和使用 Vite 环境变量配置

  1. 在项目根目录(index.html 文件所在的位置)下创建对应环境的.env文件,然后在文件中定义对应环境下的变量,默认情况下只有以 VITE_ 为前缀的变量才会暴露给 Vite:

    • .env【默认配置】:

      # 项目标题
      VITE_APP_TITLE = OCTOPUS
      
      # 运行端口号
      VITE_PORT = 8080
      
    • .env.development【开发环境】:

      # 开发环境
      VITE_USER_NODE_ENV = development
      
      # 项目基本 URL
      VITE_BASE_URL = /dev/
      
      # 启动时自动打开浏览器
      VITE_OPEN = true
      
    • .env.production【生产环境】:

      # 生产环境
      VITE_USER_NODE_ENV = production
      
      # 项目基本 URL
      VITE_BASE_URL = /
      
    • .env.test【测试环境】:

      # 测试环境
      VITE_USER_NODE_ENV = test
      
      # 项目基本 URL
      VITE_BASE_URL = /test/
      
  2. 创建src\types\global.d.ts文件声明环境变量类型:

    // 定义泛型 Recordable,键类型为字符串、值类型为 T
    declare type Recordable<T = any> = Record<string, T>
    
    // 定义接口 ViteEnv,描述项目的环境变量结构
    declare interface ViteEnv {
      VITE_USER_NODE_ENV: 'development' | 'production' | 'test' // 当前运行环境,可选值为 'development', 'production' 或 'test'
      VITE_GLOB_APP_TITLE: string // 应用标题
      VITE_PORT: number // Vite 端口号
      VITE_OPEN: boolean // 是否自动在浏览器打开应用
      VITE_REPORT: boolean // 是否开启 report 功能
      VITE_BUILD_COMPRESS: 'gzip' | 'brotli' | 'gzip,brotli' | 'none' // 可选值为 'gzip', 'brotli', 'gzip,brotli' 或 'none'
      VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE: boolean // 是否删除原始文件
      VITE_DROP_CONSOLE: boolean // 是否删除控制台
      VITE_BASE_URL: string // 基本 URL
      VITE_API_URL: string // API 地址
      VITE_PROXY: [string, string][] // 表示代理配置
      VITE_USE_IMAGEMIN: boolean // 是否使用图像压缩
    }
    
  3. 创建build\getEnv.ts文件用于完成环境变量类型转换:

    /**
     * 从 Vite 的环境变量对象中读取值并进行类型转换
     * @param envConf 原始环境变量配置对象
     * @returns ViteEnv 适用于 Vite 的环境变量对象
     */
    export function wrapperEnv(envConf: Recordable): ViteEnv {
      // 创建一个空对象,用于存储处理后的环境变量
      const ret: any = {}
    
      // 遍历环境变量对象的键
      for (const envName of Object.keys(envConf)) {
        // 将环境变量值中的 '\n' 替换为换行符 '\n'
        let realName = envConf[envName].replace(/\\n/g, '\n')
        realName = realName === 'true' ? true : realName === 'false' ? false : realName
        if (envName === 'VITE_PORT') realName = Number(realName)
        if (envName === 'VITE_PROXY') {
          try {
            realName = JSON.parse(realName)
          } catch (error) {
            // ignore
          }
        }
        ret[envName] = realName
      }
      return ret
    }
    
  4. tsconfig.json中添加 TypeScript 编译器配置:

    {
      "include": [
        "src/**/*.ts",
        "src/**/*.d.ts",
        "src/**/*.tsx",
        "src/**/*.vue",
        "build/**/*.ts",
        "build/**/*.d.ts",
        "vite.config.ts"
      ],
      "exclude": ["node_modules", "dist", "**/*.js"]
    }
    
  5. vite.config.ts中获取环境变量,并修改 Vite 启动配置:

    import { defineConfig, loadEnv, ConfigEnv, UserConfig } from 'vite'
    import { wrapperEnv } from './build/getEnv'
    
    // https://vitejs.dev/config/
    export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
      const root = process.cwd()
      // 获取.env文件中的内容
      const env = loadEnv(mode, root)
      const viteEnv = wrapperEnv(env)
    
      return {
        root, //项目根目录
        base: viteEnv.VITE_BASE_URL, //基础 URL
        server: {
          host: '0.0.0.0', //指定服务器主机地址
          port: viteEnv.VITE_PORT, //指定开发服务器端口
          strictPort: true, //若端口已被占用则会直接退出
          open: viteEnv.VITE_OPEN //服务器启动时,自动在浏览器中打开应用程序
        }
      }
    })
    
  6. 在项目中使用 Vite 提供的import.meta.env对象获取这些环境变量:

    <script setup lang="ts">
    const title = import.meta.env.VITE_APP_TITLE
    </script>
    
    <template>
      <h1>{{ title }}</h1>
    </template>
    

安装 Element Plus

  1. 使用包管理器 pnpm 安装 Element Plus:

    pnpm install element-plus
    
  2. main.ts 文件中引入 Element Plus:

    import { createApp } from 'vue'
    import ElementPlus from 'element-plus'
    import 'element-plus/dist/index.css'
    import App from './App.vue'
    
    const app = createApp(App)
    
    app.use(ElementPlus)
    app.mount('#app')
    
  3. 设置 Element Plus 默认语言为中文:

    import ElementPlus from 'element-plus'
    import zhCn from 'element-plus/es/locale/lang/zh-cn'
    
    app.use(ElementPlus, {
      locale: zhCn,
    })
    
  4. tsconfig.json 中通过 compilerOptions.type 指定全局组件类型:

    {
      "compilerOptions": {
        // ...
        "types": ["element-plus/global"]
      }
    }
    
  5. App.vue 中添加 Element Plus 按钮组件:

    <template>
      <div class="mb-4">
        <el-button>Default</el-button>
        <el-button type="primary">Primary</el-button>
        <el-button type="success">Success</el-button>
        <el-button type="info">Info</el-button>
        <el-button type="warning">Warning</el-button>
        <el-button type="danger">Danger</el-button>
      </div>
    </template>
    
  6. 执行命令启动项目:

    pnpm run dev
    

    image-20240609193421586

集成 sass 配置全局变量

  1. 通过以下命令安装 sass

    pnpm add sass
    
  2. 创建src\assets\styles\variable.scss全局变量文件:

    //全局scss变量
    $color:red
    
  3. vite.config.ts中使用 additionalData 引入全局的 Sass 变量文件:

    export default defineConfig({
      css: {
        preprocessorOptions: {
          scss: {
            javaScriptEnabled: true,
            // 向全局 scss 文件内容注入变量
            additionalData: `@import "@/assets/styles/variable.scss";`
          }
        }
      }
    })
    
  4. 在 Vue 组件中使用变量:

    <script setup lang="ts">
    // This starter template is using Vue 3 <script setup> SFCs
    </script>
    
    <template>
      <div>
        <h1>Hello world!</h1>
      </div>
    </template>
    
    <style scoped lang="scss">
    /* SCSS */
    div {
      font: 2em sans-serif;
      h1 {
        color: $color;
      }
    }
    </style>
    
  5. 执行命令启动项目:

    pnpm run dev
    

    image-20240610130819150

清除浏览器默认样式

通常,浏览器会对一些 HTML 元素应用一些默认的样式,但这些默认样式在不同浏览器之间可能存在差异,导致页面在不同浏览器中呈现不一致。

清除默认样式可以将所有元素的样式重置为统一的基础样式,然后再根据需要逐个重新定义。这样可以确保在编写样式时,不会受到浏览器默认样式的影响,从而更容易实现跨浏览器的一致性。

  1. 进入 NPM 官网:https://www.npmjs.com/,搜索 reset.scss,复制即可:

    image-20240610125420052

  2. 创建 src\assets\styles\reset.scss 文件,添加样式:

    *,
    *:after,
    *:before {
      box-sizing: border-box;
    
      outline: none;
    }
    
    html,
    body,
    div,
    span,
    applet,
    object,
    iframe,
    h1,
    h2,
    h3,
    h4,
    h5,
    h6,
    p,
    blockquote,
    pre,
    a,
    abbr,
    acronym,
    address,
    big,
    cite,
    code,
    del,
    dfn,
    em,
    img,
    ins,
    kbd,
    q,
    s,
    samp,
    small,
    strike,
    strong,
    sub,
    sup,
    tt,
    var,
    b,
    u,
    i,
    center,
    dl,
    dt,
    dd,
    ol,
    ul,
    li,
    fieldset,
    form,
    label,
    legend,
    table,
    caption,
    tbody,
    tfoot,
    thead,
    tr,
    th,
    td,
    article,
    aside,
    canvas,
    details,
    embed,
    figure,
    figcaption,
    footer,
    header,
    hgroup,
    menu,
    nav,
    output,
    ruby,
    section,
    summary,
    time,
    mark,
    audio,
    video {
      font: inherit;
      font-size: 100%;
    
      margin: 0;
      padding: 0;
    
      vertical-align: baseline;
    
      border: 0;
    }
    
    article,
    aside,
    details,
    figcaption,
    figure,
    footer,
    header,
    hgroup,
    menu,
    nav,
    section {
      display: block;
    }
    
    body {
      line-height: 1;
    }
    
    ol,
    ul {
      list-style: none;
    }
    
    blockquote,
    q {
      quotes: none;
    
      &:before,
      &:after {
        content: '';
        content: none;
      }
    }
    
    sub,
    sup {
      font-size: 75%;
      line-height: 0;
    
      position: relative;
    
      vertical-align: baseline;
    }
    
    sup {
      top: -.5em;
    }
    
    sub {
      bottom: -.25em;
    }
    
    table {
      border-spacing: 0;
      border-collapse: collapse;
    }
    
    input,
    textarea,
    button {
      font-family: inhert;
      font-size: inherit;
    
      color: inherit;
    }
    
    select {
      text-indent: .01px;
      text-overflow: '';
    
      border: 0;
      border-radius: 0;
    
      -webkit-appearance: none;
      -moz-appearance: none;
    }
    
    select::-ms-expand {
      display: none;
    }
    
    code,
    pre {
      font-family: monospace, monospace;
      font-size: 1em;
    }
    
  3. 创建 src\assets\styles\index.scss 文件,用于统一管理和维护项目的样式文件:

    @import './reset.scss';
    
  4. main.ts 文件中引入index.scss样式文件:

    import './assets/styles/index.scss'
    

安装 Tailwind CSS

  1. 打开 Tailwind CSS 官网【https://tailwindcss.com/】,点击【Docs】查看文档:

    image-20240609113814168

  2. 点击【Framework Guides】查看框架指南,我们的项目是使用 Vite 构建,所以点击【Vite】:

    image-20240609114049866

  3. 点击【Using Vue】查看安装步骤:

    image-20240609115121127

  4. 执行命令安装 Tailwind CSS:

    pnpm i -D tailwindcss postcss autoprefixer
    

    image-20240609115408956

  5. 运行命令生成 Tailwind CSS 配置文件:tailwind.config.js、postcss.config.js

    npx tailwindcss init -p
    

    image-20240609115511670

  6. tailwind.config.js配置文件中添加模板文件路径:

    content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}']
    
  7. 创建src\assets\styles\tailwind.scss文件, 添加 Tailwind CSS 提供的用于导入基础样式、组件和实用工具的特殊指令:

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
  8. src\assets\styles\index.scss 文件引入tailwind.scss,或者在main.ts文件中直接引入:

    @import './tailwind.scss';
    
  9. 在项目中使用 Tailwind.css 设置内容样式:

    <template>
      <h1 class="text-3xl font-bold underline">
        Hello world!
      </h1>
    </template>
    
  10. 执行命令启动项目:

    pnpm run dev
    

    image-20240609190157155

封装 SvgIcon 组件

  1. 安装 SVG 插件:

    pnpm install vite-plugin-svg-icons -D
    
  2. vite.config.ts中配置图标插件:

    // vite.config.ts
    import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
    import path from 'path'
    
    export default () => {
        return {
            plugins: [
                // SVG 图标插件配置
                createSvgIconsPlugin({
                    // 指定图标目录 src/assets/icons
                    iconDirs: [resolve(process.cwd(), 'src/assets/icons')],
                    // 指定生成的 symbol-id 的格式
                    symbolId: 'icon-[dir]-[name]'
                })
            ],
        }
    }
    

    这样配置之后,如果在 src/assets/icons/ui 目录中有一个名为 heart.svg 的 SVG 文件,其 symbolId 将就会是 icon-ui-heart

  3. 在入口文件(main.ts)中导入:

    // main.ts
    import 'virtual:svg-icons-register'
    
  4. 创建文件src/components/SvgIcon/index.vue,封装 SvgIcon 组件:

    <template>
      <!-- SVG 图标组件 -->
      <svg :class="iconClass" :width="width" :height="height" :fill="color" aria-hidden="true">
        <!-- 使用外部定义的图标符号 -->
        <use :xlink:href="symbolId" />
      </svg>
    </template>
    
    <script setup lang="ts">
    import { computed } from 'vue'
    
    // 定义 SvgIcon 组件的属性接口
    interface SvgProps {
      name: string // 图标的名称 (必传)
      prefix?: string // 图标前缀 (可选)
      width?: string // 图标的宽度 (可选)
      height?: string // 图标的高度 (可选)
      color?: string // 图标的填充颜色 (可选)
      iconClass?: string // 图标的类名 (可选)
    }
    
    // 设置属性的默认值
    const props = withDefaults(defineProps<SvgProps>(), {
      prefix: 'icon', // 默认前缀
      width: '20px', // 默认宽度
      height: '20px', // 默认高度
      color: 'currentColor', // 继承父元素的 color 属性,允许图标颜色随父元素的文本颜色自动变化
      iconClass: '' // 默认类名为空
    })
    
    // 计算图标的符号 ID,用于 <use> 标签的 xlink:href 属性
    const symbolId = computed(() => `#${props.prefix}-${props.name}`)
    </script>
    
    <style scoped lang="scss">
    /* 在这里添加样式 */
    </style>
    
  5. 注册组件(三选一)

    • 局部注册:使用时在 Vue 组件中直接导入。

      import svgIcon from '@/components/SvgIcon.vue'
      
    • 全局注册:在入口文件(main.ts)通过 app.component() 方法将 SvgIcon 组件在全局范围内注册到 Vue 应用。

      // main.ts
      import SvgIcon from '@/components/SvgIcon.vue'
       
      app.component('SvgIcon', SvgIcon)
      
    • 使用插件注册全局组件:

      1. src/components/index.ts中统一注册组件,并导出插件对象:

        //全局注册组件
        import SvgIcon from './SvgIcon/index.vue'
        
        //全局组件
        const globalComponents = {
          SvgIcon
        }
        
        //对外暴露插件对象
        export default {
          //install 注册组件
          install(app: any) {
            Object.keys(globalComponents).forEach((key) => {
              app.component(key, globalComponents[key])
            })
          }
        }
        
      2. 在入口文件(main.ts)安装全局组件插件:

        import GlobalComponents from '@/components/index'
        
        app.use(GlobalComponents)
        
  6. 结合iconfont-阿里巴巴矢量图标库使用组件:

    <!-- 搜索按钮 -->
    <svg-icon class="cursor-pointer" name="Search" />
    

安装 Piana 持久化插件

官网文档:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/guide/

pinia-plugin-persistedstate 是一个用于 Pinia 状态管理库的插件,作用如下:

  1. 状态持久化: 将 Pinia 中的状态数据保存到浏览器的本地存储中,使得在页面刷新或用户重新访问应用时,状态数据可以得以恢复,从而保持用户的操作和数据状态。

  2. 数据恢复: 在用户重新打开应用或者刷新页面时,可以通过读取本地存储中的数据,将之前保存的状态数据重新加载到 Pinia 的状态管理中,确保用户体验的连贯性和持久化存储的功能。

  3. 配置灵活: 可以通过插件的配置选项来指定存储数据的方式(如 localStorage、sessionStorage 或者自定义的存储引擎),以及对状态数据进行序列化和反序列化的方法。

  4. 安装pinia-plugin-persistedstate依赖:

    pnpm add pinia-plugin-persistedstate
    
  5. src/stores/index.ts中将插件添加到 pinia 实例上:

    import { createPinia } from 'pinia'
    import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
    
    // 添加 persisted state 插件,并指定可选的选项
    const pinia = createPinia()
    pinia.use(piniaPluginPersistedstate)
    
    export default pinia
    
  6. main.ts入口文件注册 Pinia:

    import { createApp } from 'vue'
    import pinia from '@/stores'
    
    import App from './App.vue'
    
    const app = createApp(App)
    
    app.use(pinia)
    app.mount('#app')
    
  7. 在创建仓库时通过persist: true参数使 Pinia 对状态数据进行持久化存储:

    • 组合式 API:

      import { defineStore } from 'pinia'
      import { ref } from 'vue'
      
      export const useStore = defineStore(
        'main',
        () => {
          const someState = ref('你好 pinia')
          return { someState }
        },
        {
          persist: true,
        },
      )
      
    • 选项式 API:

      import { defineStore } from 'pinia'
      
      export const useStore = defineStore('main', {
        state: () => {
          return {
            someState: '你好 pinia',
          }
        },
        persist: true,
      })
      
  • 40
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@赵士杰

如果对你有用,可以进行打赏,感

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值