使用vite创建vue3项目

使用vite创建vue3项目

npm install -g create-vite-app //安装全局create-vite-app
create-vite-app vue3-vite   //使用工具create-vite-app创建项目名为vue3-vite的vue3项目
cd 01-vue3-vite //进入项目文件夹
npm install //初始化项目
npm run dev //运行项目

https://blog.csdn.net/weixin_41308072/article/details/108994027

安装ts

npm install -D typescript

这里附上一个Vue3+TS的文档地址:https://24kcs.github.io/vue3_study/

编写ts配置文件

// tsconfig.json
{
 "compilerOptions": {
   // TypeScript 默认会把代码编译为 ECMAScript 3
   // esnext 表示仅仅校验转换 TypeScript 类型,不进行语法编译
   "target": "esnext",
   "module": "esnext",
   // 开启严格模式,这使得对“this”的数据属性进行更严格的推断成为可能
   "strict": true,
   "jsx": "preserve",
   "moduleResolution": "node"
},

 // 配置需要校验的文件
 "include": [
   "src/**/*.ts",
   "src/**/*.vue"
],

 // 排除不需要 TypeScript 校验的文件
 "exclude": [
   "node_modules"
]
}

添加类型声明文件

现在打包项目会报错,找不到App.vue模块相应的类型声明。

/src 目录下创建一个 .ts 文件,添加 .vue 文件的类型声明

// /src/shims-vue.d.ts
declare module '*.vue' {
// Vue 3
import { defineComponent } from 'vue'
const Component: ReturnType<typeof defineComponent>
export default Component
}

配置命令在package.json文件中

{
 "name": "vue3-vite",
 "version": "0.0.0",
 "scripts": {
   "dev": "vite", //启动项目命令
   "build": "tsc --noEmit && vite build"//打包命令
},
 "dependencies": {
   "vue": "^3.0.0-rc.1"
},
 "devDependencies": {
   "vite": "^1.0.0-rc.1",
   "@vue/compiler-sfc": "^3.0.0-rc.1"
}
}

此时打包就不出错

在根级目录和package.json同级创建vite.config.js文件配置内容

const path = require('path')
// vite.config.js # or vite.config.ts

module.exports = {
 alias: {
   // 键必须以斜线开始和结束
   '/@/': path.resolve(__dirname, './src')
},
 hostname: '10.14.14.246',//本地主机ip
 port: 8080,//端口
 // 是否自动在浏览器打开
 open: true,
 // 是否开启 https
 https: false,
 // 服务端渲染
 ssr: false,
 /**
  * 在生产中服务时的基本公共路径。
  * @default '/'
  */
 base: './',
 /**
  * 与“根”相关的目录,构建输出将放在其中。如果目录存在,它将在构建之前被删除。
  * @default 'dist'
  */
 outDir: 'dist',
 // 反向代理
 proxy: {
   '/api': {
     target: 'https://blog.csdn.net/weixin_45292658',
     changeOrigin: true,
     rewrite: path => path.replace(/^/api/, '')
  }
}
}
  • 创建src/router/index.ts文件,配置路由

import { createRouter, createWebHashHistory } from 'vue-router'
export default createRouter({
 // 指定路由模式
 history: createWebHashHistory(),
 // 路由地址
 routes: []
})
  • 安装vuex

npm install vuex@4.0   // 如果npm找不到4.0版本的换成yarn安装
yarn add vuex@4.0
  • 创建src/store/index.ts,配置vuex

import { createStore } from 'vuex'
export default createStore({
 state: {
   name: 'zhagnsan'
}
})
  • main.ts中配置router和store

import { createApp } from 'vue'
import App from './App.vue'
// 导入router和store
import router from './router/index'
import store from './store/index'

//
const app = createApp(App)
app.use(router)
app.use(store)
app.mount('#app')//挂载在#app节点上

 

不停学习,热爱是源源不断的动力。
原文地址:https://www.cnblogs.com/ximenchuifa/p/14893205.html