vite+vue3+ts搭建项目一(初始化,环境,运行)

vite+vue3+ts搭建项目一(初始化,环境,运行)

相关环境

nvm use node // Now using node v19.7.0 (npm v9.5.0)

node -v      // v19.7.0(建议16.0.0+)

npm -v       // 9.5.0

//非必要
vite -v      // vite/4.1.4 darwin-arm64 node-v19.7.0
// 安装 vite
npm install vite -g

//非必要
vue -V       // @vue/cli 5.0.8
// 安装 vue/cli
npm install -g @vue/cli

如果npm版本太低,无法运行

初始化项目

npm create vite@latest
Need to install the following packages:
  [email protected]
Ok to proceed? (y) y
✔ Project name: … vitetest
? Select a framework: › - Use arrow-keys. Return to submit.
    Vanilla
❯   Vue
    React
    Preact
    Lit
    Svelte
    Others
? Select a variant: › - Use arrow-keys. Return to submit.
    JavaScript
❯   TypeScript
    Customize with create-vue ↗
    Nuxt ↗

Scaffolding project in xx/vitetest...

Done. Now run:

  cd vitetest
  npm install
  npm run dev

项目目录如下

配置文件为vite.config.ts

运行

cd xx/vitetest

// 安装依赖包
npm install

// 运行
npm run dev
> [email protected] dev
> vite

  VITE v4.1.4  ready in 385 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h to show help

打包

npm run build

> [email protected] build
> vue-tsc && vite build

vite v4.1.4 building for production...
✓ 18 modules transformed.
dist/index.html                  0.45 kB
dist/assets/vue-5532db34.svg     0.50 kB
dist/assets/index-08cab964.css   1.30 kB │ gzip:  0.67 kB
dist/assets/index-316eef2e.js   54.50 kB │ gzip: 21.98 kB

项目结构如上图,打包后会生成dist目录

vscode设置

扩展 -> 搜索
禁用vetur,安装使用typescript volar

配合ts语法糖的vue3生命周期函数

<template>
  home
</template>

<script setup lang="ts">
import {
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  onActivated,
} from 'vue'

// 通过compositon-api的形式去使用生命周期钩子

// 创建之前(无法读取dom)
onBeforeMount(() => {
  console.log("创建之前");
});
// 创建完成(可以读取dom)
onMounted(() => {
  console.log("创建完成");
});
// 更新之前(读取更新之前的dom)
onBeforeUpdate(() => {
  console.log("更新之前");
});
// 更新完成(读取更新之后的dom)
onUpdated(() => {
  console.log("更新完成");
});
// 卸载之前
onBeforeUnmount(() => {
  console.log("卸载之前");
});
// 卸载完成
onUnmounted(() => {
  console.log("卸载完成");
});

</script>

<style lang = "scss" scoped></style>

原文链接:http://guohaonan1.github.io/2023/04/22/vite-vue3-ts搭建项目一(初始化,环境,运行)/

猜你喜欢

转载自blog.csdn.net/qq_23858785/article/details/130307448