vue3+vite配置多頁面

通過配置多頁面應用,從而將給子模塊依賴分隔開各自加載,可以減少初始資源的請求,加快頁面的訪問速度。
比如我們有很多H5頁面,並且相互獨立,比如報修,購卡,計價規則等等,那我們如果訪問購卡,只需要通過/buyCards/進行訪問,不需要初始資源的加載支持。

目錄結構

├── build       打包後的靜態資源目錄
├── mock            mock服務 todo
└── src             項目資源目錄
    └── assets          項目靜態資源
    ├── common          全局方法公共庫
        └── utils.ts            全局公共方法
        └── constants.ts        全局公共常量
    ├── components      公共組件
    ├── interface       公共模型
    ├── pages           頁面模塊
        ├── xxx         頁面模塊A
            ├── apis            接口定義
            ├── components      頁面組件
            └── router          路由配置
            └── store           store配置
            └── common           模塊公共庫
                └── utils.ts           模塊公共工具方法
                └── constants.ts        模塊常量
                └── eventMap.ts         模塊埋點枚舉
            └── views           模塊頁面
            └── App.vue         入口根節點
            └── index.html      入口頁面
            └── main.ts         入口頁面文件
        ├── xxx         頁面模塊B
            ├── apis            接口定義
            ├── components      頁面組件
            └── router          路由配置
            └── store           store配置
            └── common           模塊公共庫
                └── utils.ts           模塊公共工具方法
                └── constants.ts        模塊常量
                └── eventMap.ts         模塊埋點枚舉
            └── views           模塊頁面
            └── App.vue         入口根節點
            └── index.html      入口頁面
            └── main.ts         入口頁面文件
        ├── xxx         初始化入口文件
    ├── style                   公共樣式模塊
    ├── types                   依賴庫類型定義
    └── .browserslistrc         瀏覽器兼容配置
    └── .eslintignore           eslint忽略文件配置
    └── .eslintrc.cjs           eslint規則配置
    └── .gitignore              gitignore配置
    └── .prettierignore         prettier忽略文件配置
    └── .prettierrrc.js         prettier文件配置
    └── .vue.config.ts          項目打包配置文件

src/index.html是默認啓動初始化項目時候的一個入口文件,代碼如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>初始化頁面路由</title>
</head>
<body>
  <p><a href="">重定向頁面</a></p>
<script>
</script>
</body>
</html>

vite配置多頁面 vite.config

修改root

修改root參數爲多頁面的根目錄: 根據不同的目錄結構而修改
● 類型: string
● 默認: process.cwd()
項目根目錄(index.html 文件所在的位置)。可以是一個絕對路徑,或者一個相對於該配置文件本身的相對路徑。
根據上述目錄工程裏,所以修改爲root: './src/pages'

修改base

base修改爲'/',避免後續打包路徑有問題
● 類型: string
● 默認: /
開發或生產環境服務的公共基礎路徑。合法的值包括以下幾種:
● 絕對 URL 路徑名,例如 /foo/
● 完整的 URL,例如 https://foo.com/
● 空字符串或 ./(用於嵌入形式的開發)

修改build.outDir

outDir: resolve(process.cwd(), 'build'), // 指定輸出路徑(相對於 項目根目錄)
● 類型: string
● 默認: dist
指定輸出路徑(相對於 項目根目錄).

修改rollupOptions.input

rollupOptions.input配置多個頁面的輸入,可以動態根據/pages文件夾下讀取,可參考如下代碼

const getEntryPath = (globPath: string) => {
  const pageEntry = {}
  glob.sync("./src/pages/**/index.html").forEach((entry: string) => {
    const pathArr: string = entry.split("/");
    const name: string = pathArr[pathArr.length - 2];
    pageEntry[name] = join(process.cwd(), `/src/pages/${name}/index.html`)
  })
  delete pageEntry.pages
  delete pageEntry.index //此處是爲了刪除初始化頁面,這個可根據頁面需要自行決定
  return pageEntry // 整體效果如下圖
}

// 自定義底層的 Rollup 打包配置
rollupOptions: {
  input: getEntryPath()
}

訪問頁面

頁面A:http://127.0.0.1:8080/newWallet/index.html#/
頁面B:http://127.0.0.1:8080/demo/index.html#/

以下是完整vite.config 僅供參考

import { defineConfig,loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path, { resolve, join } from 'path'
import autoprefixer from 'autoprefixer';
import postCssPxToRem from 'postcss-pxtorem';
import AutoImport from "unplugin-auto-import/vite"
import glob from "glob";
import eslintPlugin from 'vite-plugin-eslint' //導入包

const assetsPath = (path: string) => {
  return join('static', path)
}

const getEntryPath = (globPath: string) => {
  const pageEntry = {}
  glob.sync("./src/pages/**/index.html").forEach((entry: string) => {
    const pathArr: string = entry.split("/");
    const name: string = pathArr[pathArr.length - 2];
    pageEntry[name] = join(process.cwd(), `/src/pages/${name}/index.html`)
  })
  delete pageEntry.pages
  delete pageEntry.index
  console.log(pageEntry)
  return pageEntry
}

export default defineConfig({
  root: './src/pages',
  base: '/',     
  define: {},
  plugins: [
    vue(),
    AutoImport ({
      imports: ["vue", "vue-router", "pinia"], // 自動導入vue和vue-router相關函數(只有組件裏哦,ts或js文件裏面不行~~~)
      dts: 'types/auto-import.d.ts' //生成全局引入的文件
    }),
    // 增加下面的配置項,這樣在運行時就能檢查eslint規範
    eslintPlugin({
      include: ['src/**/*.js', 'src/**/*.vue', 'src/*.js', 'src/*.vue'],
      exclude: ['./node_modules/**', './src/types/**'],
      cache: false
    }),
  ],    
  resolve: { 
    alias: [
      {
        find: "@",
        replacement: resolve(__dirname, "src")
      }
    ] 
  },  
  css: {
    postcss: {
      plugins: [
        autoprefixer({
          overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 8'],
        }),
        postCssPxToRem({
          // 自適應,px>rem轉換
          rootValue: 75, // 75表示750設計稿,37.5表示375設計稿
          propList: ['*'], // 需要轉換的屬性,這裏選擇全部都進行轉換
          selectorBlackList: ['norem'], // 過濾掉norem-開頭的class,不進行rem轉換
        }),
      ],
    }
  },
  server: {
    host: 'localhost',        // 指定服務器應該監聽哪個 IP 地址
    port: 8080,               // 端口
    strictPort: false, // 若端口已被佔用,嘗試下移一格端口
    open: true,   
    proxy: {                
      '/gateway': {
        target: process.env.VITE_API_URL || 'https://pinzhi.didichuxing.com',
        ws: true,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
  build: {
    outDir: resolve(process.cwd(),'build'),// 指定輸出路徑(相對於 項目根目錄)
    sourcemap: false, // 構建後是否生成 source map 文件
    chunkSizeWarningLimit: 1500, // 規定觸發警告的 chunk(文件塊) 大小
    assetsDir: 'static',
    minify: 'esbuild',
    rollupOptions: {  // 自定義底層的 Rollup 打包配置
      input: getEntryPath(), 
      output: {
        entryFileNames: assetsPath('js/[name].js'),
        chunkFileNames: assetsPath('js/[name].js'),
        assetFileNames: assetsPath('css/[name].[ext]'),
        compact: true,
        manualChunks: (id: string) => {
          if(id.includes("node_modules")) {
            return id.toString().split('node_modules/')[1].split('/')[0].toString(); // 拆分多個vendors
          }
        }
      },
    },
    emptyOutDir: true,
  }
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章