<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Vite 開發(fā)快速入門

          共 19125字,需瀏覽 39分鐘

           ·

          2021-08-01 10:03

          微信搜索逆鋒起筆關注后回復編程pdf
          領取編程大佬們所推薦的 23 種編程資料!

          作者:xiangzhihong

          來源:SegmentFault 思否社區(qū)

          一、Vite簡介

          Vite (法語意為 "快速的",發(fā)音 /vit/) 是一種面向現(xiàn)代瀏覽器的一個更輕、更快的前端構建工具,能夠顯著提升前端的開發(fā)體驗。除了Vite外,前端著名的構建工具還有Webpack和Gulp。目前,Vite已經(jīng)發(fā)布了Vite2,Vite全新的插件架構、絲滑的開發(fā)體驗,可以和Vue3的完美結合。

          1.1 Vite組成

          Vite構建工具由兩部分組成:

          • 一個開發(fā)服務器,它基于原生 ES 模塊提供了豐富的內(nèi)建功能,如模塊熱更新(HMR)。

          • 一套構建指令,它使用 Rollup 打包你的代碼,并且它是預配置的,可以輸出用于生產(chǎn)環(huán)境的優(yōu)化過的靜態(tài)資源。


          總的來說,Vite希望提供開箱即用的配置,同時它的插件API和JavaScript API帶來了高度的可擴展性。不過,相比Vue-cli配置來說,Vite構建的項目還是有很多的配置需要開發(fā)者自己進行處理。

          1.2 瀏覽器支持

          • 開發(fā)環(huán)境中:Vite需要在支持原生 ES 模塊動態(tài)導入的瀏覽器中使用。

          • 生產(chǎn)環(huán)境中:默認支持的瀏覽器需要支持 通過腳本標簽來引入原生 ES 模塊 。可以通過官方插件 @vitejs/plugin-legacy 支持舊瀏覽器。

          二、環(huán)境搭建

          2.1 創(chuàng)建項目

          根據(jù)Vite官網(wǎng)介紹,我們可以使用npm或yarn來初始化Vite項目,并且Node.js的版本需要 >= 12.0.0。
          使用 NPM方式
          npm init vite@latest 項目名
          使用 Yarn方式
          yarn create vite 項目名
          除此之外,還可以通過附加的命令行選項直接指定項目名稱和模板。例如,要構建一個 Vite + Vue 項目,命令如下:
          # npm 6.x
          npm init @vitejs/app my-vue-app --template vue

          # npm 7+, 需要額外的雙橫線:
          npm init @vitejs/app my-vue-app -- --template vue

          # yarn
          yarn create @vitejs/app my-vue-app --template vue
          輸入完命令之后,按照提示操作即可。如果項目需要支持TypeScript,可以在初始化項目的時候選擇vue-ts。項目創(chuàng)建好之后,可以發(fā)現(xiàn)Vite所創(chuàng)建好的項目其實與使用Vue-cli所創(chuàng)建的項目目錄結構其實是差不多的。

          2.2 集成Vue-Router

          2.2.1 安裝配置Vue-Router

          Vue-Router作為大多數(shù)項目必不可少的路由工具,已經(jīng)被大多數(shù)的前端項目所使用,Vue-Router可以讓構建單頁面應用變得更加的容易。首先,在項目中安裝Vue-Router,安裝命令如下:
          //npm
          npm install vue-router@next --save

          //yarn
          yarn add vue-router@next --save
          安裝完成之后,在src目錄下創(chuàng)建一個文件夾router/index.ts,然后添加如下一些配置:
          import { createRouter, createWebHashHistory } from 'vue-router';

          const router = createRouter({
            history: createWebHashHistory(),
            routes: [
              { path: '/', component: () => import('views/home.vue') }
            ]
          });

          export default router
          然后,我們在main.ts文件中引入Vue-Router,如下所示。
          import router from './router';
          createApp(App).use(router).mount("#app");

          2.2.2 新增路由頁面

          為了方便掩飾,我們再新增兩個路由頁面。熟悉,創(chuàng)建pages文件夾,把需要展示的頁面創(chuàng)建完成。然后,我們在router/index.ts注冊我們新增的頁面,如下所示。
          routes: [
                  {
                      path: "/home",
                      name: "Home",
                      alias"/",
                      component: () => import("../pages/Home.vue")
                  },
              ]
          接下來,我們再修改一下App.vue的代碼,如下所示。
          <template>
            <router-link to="/home">Home</router-link>
            <router-link to="/about">About</router-link>
            <router-view></router-view>
          </template>

          <script lang="ts">
          import { defineComponent } from 'vue'

          export default defineComponent({
            name: 'App'
          })
          </script>
          接下來啟動服務,就可以看到所配置的頁面了,并且點擊還能夠跳轉到對應的頁面。

          2.3 集成Vuex

          Vuex 是一個專為 Vue.js 應用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應用的所有組件的狀態(tài),并以相應的規(guī)則保證狀態(tài)以一種可預測的方式發(fā)生變化。Vuex 也集成到 Vue 的官方調(diào)試工具 devtools extension (opens new window),提供了諸如零配置的 time-travel 調(diào)試、狀態(tài)快照導入導出等高級調(diào)試功能。
          使用Vuex之前,需要先安裝Vuex插件,如下所示。
          //npm
          npm install vuex@next --save

          //yarn
          yarn add vuex@next --save
          安裝完成之后,需要先初始化Vuex。首先,創(chuàng)建一個store/index.ts文件,添加如下代碼。
          import { createStore } from "vuex";

          const store = createStore({
            modules: {
              home: {
                namespaced: true,
                state: {
                  count: 1
                },
                mutations: {
                  add(state){
                    state.count++;
                  }
                }
              }
            }
          })

          export default store;
          上面的代碼作用就是實現(xiàn)一個簡單的自加功能。然后,我們在main.js文件中引入Vuex。
          import { createApp } from 'vue';
          import App from './App.vue';

          import store from "./store";

          const app = createApp(App);
          app.use(store);
          app.mount('#app');
          完成上述操作之后,接下來我們給Vuex編寫一個測試代碼看Vuex是否有效。修改Home.vue的代碼如下。
          <template>
            <h1>Home Page</h1>
            <h2>{{count}}</h2>
            <button @click="handleClick">click</button>
          </template>

          <script lang="ts">
          import { defineComponent, computed } from 'vue';
          import { useStore } from 'vuex';

          export default defineComponent({
            setup () {
              const store = useStore();
              const count = computed(() => store.state.home.count);
              const handleClick = () => {
                store.commit('home/add');
              };
              return {
                handleClick,
                count
              };
            }
          })
          </script>
          上面的代碼實現(xiàn)的就是一個簡單的自加功能,和默認示例工程的效果事一樣的,只不過我們使用Vuex。

          2.4 集成Eslint

          ESLint是一個用來識別 ECMAScript語法, 并且按照規(guī)則給出報告的代碼檢測工具,使用它可以避免低級錯誤和統(tǒng)一代碼的風格。集成Eslint需要安裝如下一些插件:
          npm方式
          npm install eslint -D
          npm install eslint-plugin-vue -D
          npm install @vue/eslint-config-typescript -D
          npm install @typescript-eslint/parser -D
          npm install @typescript-eslint/eslint-plugin -D
          npm install typescript -D
          npm install prettier -D
          npm install eslint-plugin-prettier -D
          npm install @vue/eslint-config-prettier -D
          yarn方式
          yarn add eslint --dev
          yarn add eslint-plugin-vue --dev
          yarn add @vue/eslint-config-typescript --dev
          yarn add @typescript-eslint/parser --dev
          yarn add @typescript-eslint/eslint-plugin --dev
          yarn add typescript --dev
          yarn add prettier --dev
          yarn add eslint-plugin-prettier --dev
          yarn add @vue/eslint-config-prettier --dev
          安裝完成之后,還需要根目錄下創(chuàng)建一個.eslintrc文件,如下。
          {
            "root"true,
            "env": {
              "browser"true,
              "node"true,
              "es2021"true
            },
            "extends": [
              "plugin:vue/vue3-recommended",
              "eslint:recommended",
              "@vue/typescript/recommended"
            ],
            "parserOptions": {
              "ecmaVersion": 2021
            }
          }
          添加了配置規(guī)則之后,還需要在package.json文件的scripts中添加如下命令:
          {
              "lint""eslint --ext src/**/*.{ts,vue} --no-error-on-unmatched-pattern"
          }
          接下來運行一下yarn lint就可以了,可以通過eslint完成格式的校驗了。不過,我們在執(zhí)行yarn lint的時候會把所有的文件全部都校驗一次,如果有很多文件的話,那么校驗起來速度將會很慢,此時,我們一般只在git提交的時候才對修改的文件進行eslint校驗,那么我們可以這么做。
          那就需要使用 lint-staged插件。
          //npm
          npm install lint-staged -D
          //yarn 
          yarn add lint-staged --dev
          然后,我們對package.json進行修改:
          {
            "gitHooks": {
              "commit-msg""node scripts/commitMessage.js",
              "pre-commit""lint-staged"
            },
            "lint-staged": {
              "*.{ts,vue}""eslint --fix"
            },
            "scripts": {
              "test:unit""jest",
              "test:e2e""cypress open",
              "test""yarn test:unit && npx cypress run",
              "lint""npx prettier -w -u . && eslint --ext .ts,.vue src/** --no-error-on-unmatched-pattern",
              "bea""npx prettier -w -u ."   
            },
          }

          2.5 配置alias

          在過去使用vue-cli的時候,我們總是使用@去引入某些文件,由于Vite沒有提供類似的配置,所以我們需要手動的對其進行相關配置,才能繼續(xù)使用@符號去快捷的引入文件。首先,我們需要修改vite.config.ts的配置。
          import { defineConfig } from 'vite';
          import vue from '@vitejs/plugin-vue';
          import { join } from "path";

          // https://vitejs.dev/config/
          export default defineConfig({
            plugins: [vue()],
            resolve: {
              alias: [
                {
                  find: '@',
                  replacement: '/src',
                },
                { find: 'views', replacement: '/src/views' },
                { find: 'components', replacement: '/src/components' },
              ]
            }
          });
          然后,我們在修改tsconfig.json文件,如下。
          {
            "compilerOptions": {
              "target""esnext",
              "module""esnext",
              "moduleResolution""node",
              "strict"true,
              "jsx""preserve",
              "sourceMap"true,
              "resolveJsonModule"true,
              "esModuleInterop"true,
              "lib": ["esnext""dom"],
             
             //以下為需要添加內(nèi)容
              "types": ["vite/client""jest"],
              "baseUrl"".",
              "paths": {
                "@/*": ["src/*"]
              } 
            },
            "include": [
              "src/**/*.ts",
              "src/**/*.d.ts",
              "src/**/*.tsx",
              "src/**/*.vue",
            ]
          }

          2.6 集成element-plus

          Element Plus是由餓了么大前端團隊開源出品的一套為開發(fā)者、設計師和產(chǎn)品經(jīng)理準備的基于 Vue 3.0 的組件庫,可以幫助開發(fā)者快速的開發(fā)網(wǎng)站,如果你使用過element-ui,那么可以快速的過渡到element-plus。除了element-plus,支持Vue 3.0 的UI框架還有很多。
          首先,在項目的根目錄下安裝element-plus,命令如下:
          npm install element-plus --save

          2.6.1 引入element-plus

          我們可以引入整個 element-plus,也可以根據(jù)需要僅引入部分組件。如果是全部引入,只需要在main.js 添加如下代碼即可。
          import { createApp } from 'vue'
          import ElementPlus from 'element-plus';
          i

          const app = createApp(App)
          app.use(ElementPlus)
          app.mount('#app')
          如果為了減小項目的包體積,那么只需要引入對應的功能組件即可。首先,安裝 babel-plugin-component插件,如下所示。
          npm install babel-plugin-component --save
          然后,修改.babelrc的配置內(nèi)容。
          {
            "plugins": [
              [
                "component",
                {
                  "libraryName""element-plus",
                  "styleLibraryName""theme-chalk"
                }
              ]
            ]
          }
          如果我們只需要引入部分組件,比如 Button 和 Select組件,那么需要在 main.js 中引入對應的組件即可,如下所示。
          import { createApp } from 'vue'
          import { store, key } from './store';
          import router from "./router";
          import { ElButton, ElSelect } from 'element-plus';
          import App from './App.vue';
          import './index.css'

          const app = createApp(App)
          app.component(ElButton.name, ElButton);
          app.component(ElSelect.name, ElSelect);

          /* 或者
           * app.use(ElButton)
           * app.use(ElSelect)
           */

          app.use(store, key)
          app.use(router)
          app.mount('#app')

          2.6.2 添加配置

          引入 Element Plus后,我們可以添加一個全局配置對象。該對象目前支持 size 與 zIndex 字段。size 用于改變組件的默認尺寸,zIndex 設置彈框的初始 z-index。以下是兩種不同的引入方式:
          全局引入:
          import { createApp } from 'vue'
          import ElementPlus from 'element-plus';
          import App from './App.vue';

          const app = createApp(App)
          app.use(ElementPlus, { size: 'small', zIndex: 3000 });
          按需引入:
          import { createApp } from 'vue'
          import { ElButton } from 'element-plus';
          import App from './App.vue';

          const app = createApp(App)
          app.config.globalProperties.$ELEMENT = option
          app.use(ElButton);

          2.6.3 配置proxy 和 alias

          如果要在Vite中使用alias別名配置和proxy代理配置,那么需要在vite.config.ts文件中進行單獨的配置。
          import { defineConfig } from 'vite'
          import vue from '@vitejs/plugin-vue'
          import styleImport from 'vite-plugin-style-import'
          import path from 'path'

          // https://vitejs.dev/config/
          export default defineConfig({
            plugins: [
              vue(),
              styleImport({
                libs: [
                  {
                    libraryName: 'element-plus',
                    esModule: true,
                    ensureStyleFile: true,
                    resolveStyle: (name) => {
                      return `element-plus/lib/theme-chalk/${name}.css`;
                    },
                    resolveComponent: (name) => {
                      return `element-plus/lib/${name}`;
                    },
                  }
                ]
              })
            ],

            /**
             * 在生產(chǎn)中服務時的基本公共路徑。
             * @default '/'
             */
            base: './',
            /**
            * 與“根”相關的目錄,構建輸出將放在其中。如果目錄存在,它將在構建之前被刪除。
            * @default 'dist'
            */
            // outDir: 'dist',
            server: {
              // hostname: '0.0.0.0',
              host: "localhost",
              port: 3001,
              // // 是否自動在瀏覽器打開
              // open: true,
              // // 是否開啟 https
              // https: false,
              // // 服務端渲染
              // ssr: false,
              proxy: {
                '/api': {
                  target: 'http://localhost:3333/',
                  changeOrigin: true,
                  ws: true,
                  rewrite: (pathStr) => pathStr.replace('/api''')
                },
              },
            },
            resolve: {
              // 導入文件夾別名
              alias: {
                '@': path.resolve(__dirname, './src'),
                views: path.resolve(__dirname, './src/views'),
                components: path.resolve(__dirname, './src/components'),
                utils: path.resolve(__dirname, './src/utils'),
                less: path.resolve(__dirname, "./src/less"),
                assets: path.resolve(__dirname, "./src/assets"),
                com: path.resolve(__dirname, "./src/components"),
                store: path.resolve(__dirname, "./src/store"),
                mixins: path.resolve(__dirname, "./src/mixins")
              },
            }
          })
          其中,vite-plugin-style-import是一個可以按需引入樣式的庫。

          三、數(shù)據(jù)請求

          Vue本身是不支持ajax調(diào)用的,如果需要執(zhí)行網(wǎng)絡請求,那么就需要借助一些工具,如superagent和axios。不過,Vue開發(fā)使用得比較多的還是axios。
          //npm
          npm insall axios -save

          //yarn 
          yarn add axios -save
          然后,新建一個request.ts,添加如下的代碼。
          import axios from 'axios';

          let request = axios.create({
              baseURL: 'http://localhost:3555/api'
          })

          export default request;
          然后,在新建一個index.ts,用來處理具體的網(wǎng)絡請求,比如:
          import request from "./axios";

          export const getUrl = () => {
              return request({
                  url: "/users/test" // 請求地址
              })
          }

          export default { getUrl };
          最后,在我們的頁面代碼中調(diào)用上面定義的接口即可。
          import { getUrl } from "../api/index"

          export default {
              setup() {
                  const getUrls = async() =>{
                      const res = await getUrl()
                      console.log(res)
                  }
                  onMounted(() => { 
                      getUrls()
                  })
              }
          }


          逆鋒起筆是一個專注于程序員圈子的技術平臺,你可以收獲最新技術動態(tài)最新內(nèi)測資格BAT等大廠大佬的經(jīng)驗增長自身學習資料職業(yè)路線賺錢思維,微信搜索逆鋒起筆關注!

          這本書讓你徹底擺脫重復繁瑣工作!
          鴻蒙操作系統(tǒng)入門到精通.pdf
          萬字詳解!Git 入門最佳實踐
          在 Google 中輸入這 4 個單詞,竟然得到了這個?
          App 開放接口 api 安全:Token 簽名 sign 的設計與實現(xiàn)

          瀏覽 58
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  亚洲免费在线观看的高清视频网站 | 青青自拍视频免费观看 | 国产免费一级A片 | 一级a爱视频 | 久久久久久久久久久久久久久久久久久久 |