使用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節點上

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM