溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vite.config.js怎么配置

發(fā)布時間:2022-02-07 16:09:13 來源:億速云 閱讀:601 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了vite.config.js怎么配置的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇vite.config.js怎么配置文章都會有所收獲,下面我們一起來看看吧。

1 如何創(chuàng)建vite項目?

step 1 :
 npm init vite@latest
 yarn create vite
step2 :
npm init vite@latest my-vue-app --template vue
 
npm 7+, 需要額外的雙橫線:
npm init vite@latest my-vue-app -- --template vue
 
# yarn
yarn create vite my-vue-app --template vue

2 如何讓vite項目啟動時自動打開瀏覽器?

注:vite針對開發(fā)環(huán)境,打包環(huán)境和預(yù)覽環(huán)境分別定義了三個選項: server、build、preview。 開發(fā)環(huán)境server類似于webpack中的devServer。

export default ({mode})=>{
return defineConfig({
  server:{
    open:true, //vite項目啟動時自動打開瀏覽器
  },
}
}

3vite啟動默認端口為3000?如何更改默認端口?

export default ({mode})=>{
return defineConfig({
  server:{
    port:8080, //vite項目啟動時自定義端口
  },
}
}

4 vite如何設(shè)置熱更新?

vite默認開發(fā)環(huán)境關(guān)閉了熱更新。代碼更改需要手動更新,設(shè)置更改代碼自動刷新頁面需要設(shè)置hmr:true

export default ({mode})=>{
return defineConfig({
  server:{
    hmr:true, //開啟熱更新
  },
}
}

5vite中如何配置別名路徑?

設(shè)置resolver選項

import { resolve } from 'path';
 
export default ({mode})=>{
return defineConfig({
  resolve:{
      alias:{
        "@":resolve(__dirname,"src"),
        "@c":resolve(__dirname,"src/components"),
      }
  },
}
}

6 vite中如何設(shè)置便捷圖片路徑引用?

比如圖片資源都在src/assets/image目錄下,不想在項目中每次都通過require("../assets/image/1.jpg")這樣寫一長串去引用。能否通過 類似nuxt中的快速引用?

  <img src="/images/1.png" alt="" />
  這里直接引用
export default ({mode})=>{
return defineConfig({
  resolve:{
      alias:{
      "/images":"src/assets/images/"
      //這里不能通過path模塊解析路徑的寫法
      }
  },
}
}

7如何把vite打包以后的js,css和img資源分別分門別類在js/css/img文件夾中?

//由于是處理打包以后的資源,所以需要配置build選項
export default ({mode})=>{
return defineConfig({
   build:{
    assetsDir:"static",
    rollupOptions:{
      
      input:{
        index:resolve(__dirname,"index.html"),
        project:resolve(__dirname,"project.html")
      },
      output:{
        chunkFileNames:'static/js/[name]-[hash].js',
        entryFileNames:"static/js/[name]-[hash].js",
        assetFileNames:"static/[ext]/name-[hash].[ext]"
      }
    },
  },
 
}
}

8 如何通過vite給項目配置多個環(huán)境?

以開發(fā)、測試和生產(chǎn)環(huán)境為例

(1)在項目根目錄下分別新建.env.development,.env.test,.env.production文件

//.env.devopment文件內(nèi)容
NODE_ENV="development"
VITE_APP_BASEAPI="https://www.dev.com"
//.env.test文件內(nèi)容
NODE_ENV="test"
VITE_APP_BASEAPI="https://www.test.com"
//.env.production文件內(nèi)容
NODE_ENV="production"
VITE_APP_BASEAPI="https://www.production.com"

(2) package.json文件做如下修改

 "scripts": {
    "dev": "vite --mode development",
    "build": "vite build --mode production",
    "test": "vite build --mode test",
    "preview": "vite preview"
  },

(3)項目中通過Import.meta.env.VITE_APP_BASEAPI來獲取對應(yīng)環(huán)境的值

<template>
  <div>
    <Item></Item>
  </div>
 
</template>
<script setup>
    import { defineComponent, onMounted, ref } from 'vue'
    import Item from "@c/item.vue"
    console.log("env", import.meta.env.VITE_APP_BASEAPI)
    console.log("可選鏈", obj?.gender || "male")
})
</script>

9 vite中如何配置多入口,進行多頁面開發(fā)?

step1:在根目錄新建一個入口頁面以project.html為例,同時在根目錄下新建一個project文件夾,在此文件夾新建一個main.js,App.vue

vite.config.js怎么配置

step2:vite.config.js作如下修改:

import { defineConfig,loadEnv  } from 'vite'
import {resolve} from "path";

export default ({mode})=>{
return defineConfig({
  build:{
    rollupOptions:{
      input:{
        index:resolve(__dirname,"index.html"),
        project:resolve(__dirname,"project.html")
      },
     //output:{
       // chunkFileNames:'static/js/[name]-[hash].js',
        //entryFileNames:"static/js/[name]-[hash].js",
        //assetFileNames:"static/[ext]/name-[hash].[ext]"
      }
    },
  },

  plugins: [
    vue(),
  ]
})

}

 step3:vite run dev 啟動以后在url加上project.html查看project項目 localhost:3000/project.html

10 如何設(shè)置開啟生產(chǎn)打包分析文件大小功能?類似webpack-bundle-analyzer?

//1 安裝rollup-plugin-visualizer 插件
npm i rollup-plugin-visualizer
//2 vite.config.js中引入插件
import {visualizer} from "rollup-plugin-visualizer"
export default ({mode:string})=>{
 
  const plugins=[ 
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()]
    }),
    visualizer({
        open:true,  //注意這里要設(shè)置為true,否則無效
        gzipSize:true,
        brotliSize:true
     })
  ];
 }
 return  defineConfig({
            
            resolve:{
              alias:{
                "@":resolve(__dirname,"src"),
                "/images":"src/assets/images/"
              }
            },
            plugins
          })

11 如何解決require is not define報錯的的問題? 場景: 比如我們assets文件夾下有一個靜態(tài)的json:

        list:[
            {
                shop_id:1,
                shop_name:'搜獵人藝術(shù)生活',
                products:[
                    {
                        pro_id:101,
                        text:'洗面奶洗面奶洗面奶洗面奶洗面奶洗面奶洗面奶洗面奶',
                        price:480,
                        num:1,
                        img:require("./images/1.png"),
                        sum:480,
                        checked:false//商品選中狀態(tài)
                    },
                    {
                        pro_id:102,
                        text:'花露水花露水花露水花露水花露水花露水花露水花露水',
                        price:680,
                        num:1,
                        img:require('./images/2.png'),
                        sum:680,
                        checked:false
                    },
                    {
                        pro_id:103,
                        text:'燕麥片燕麥片燕麥片燕麥片燕麥片燕麥片燕麥片燕麥片',
                        price:380,
                        num:1,
                        img:require('./images/3.png'),
                        sum:380,
                        checked:false
                    }
                ],
                check:false,//店鋪選中狀態(tài)
                choose:0,//商品選中個數(shù)
            },
            {
                shop_id:2,
                shop_name:'卷卷旗艦店',
                products:[
                    {
                        pro_id:201,
                        text:'剃須刀剃須刀剃須刀剃須刀剃須刀剃須刀剃須刀剃須刀',
                        price:580,
                        num:1,
                        img:require('./images/4.png'),
                        sum:580,
                        checked:false
                    },
                    {
                        pro_id:202,
                        text:'衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙',
                        price:780,
                        num:1,
                        img:require('./images/5.png'),
                        sum:780,
                        checked:false
                    }
                ],
                check:false,
                choose:0,
            },
           
        ],
    status:false,//全選選中狀態(tài)
    allchoose:0,//店鋪選中個數(shù)
    allsum:0,//總計價格
    allnum:0,//總計數(shù)量
}
export default fetchData

此時運行你回發(fā)現(xiàn)報錯:require is not define? 解決辦法:

const fetchData={
        list:[
            {
                shop_id:1,
                shop_name:'搜獵人藝術(shù)生活',
                products:[
                    {
                        pro_id:101,
                        text:'洗面奶洗面奶洗面奶洗面奶洗面奶洗面奶洗面奶洗面奶',
                        price:480,
                        num:1,
                        img:new URL("./images/1.png",import.meta.url).href,
                        sum:480,
                        checked:false//商品選中狀態(tài)
                    },
                    {
                        pro_id:102,
                        text:'花露水花露水花露水花露水花露水花露水花露水花露水',
                        price:680,
                        num:1,
                        img:new URL('./images/2.png',import.meta.url).href,
                        sum:680,
                        checked:false
                    },
                    {
                        pro_id:103,
                        text:'燕麥片燕麥片燕麥片燕麥片燕麥片燕麥片燕麥片燕麥片',
                        price:380,
                        num:1,
                        img:new URL('./images/3.png',import.meta.url).href,
                        sum:380,
                        checked:false
                    }
                ],
                check:false,//店鋪選中狀態(tài)
                choose:0,//商品選中個數(shù)
            },
            {
                shop_id:2,
                shop_name:'卷卷旗艦店',
                products:[
                    {
                        pro_id:201,
                        text:'剃須刀剃須刀剃須刀剃須刀剃須刀剃須刀剃須刀剃須刀',
                        price:580,
                        num:1,
                        img:new URL('./images/4.png',import.meta.url).href,
                        sum:580,
                        checked:false
                    },
                    {
                        pro_id:202,
                        text:'衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙衛(wèi)生紙',
                        price:780,
                        num:1,
                        img:new URL('./images/5.png',import.meta.url).href,
                        sum:780,
                        checked:false
                    }
                ],
                check:false,
                choose:0,
            },
            
        ],
    status:false,//全選選中狀態(tài)
    allchoose:0,//店鋪選中個數(shù)
    allsum:0,//總計價格
    allnum:0,//總計數(shù)量
}
export default fetchData

注意引用方式的變化:require------->new URL('./images/5.png',import.meta.url).href

關(guān)于“vite.config.js怎么配置”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“vite.config.js怎么配置”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI