VUE cli 4.x下配置多頁面以及同時配置支持element-ui及mint-ui並且優化首頁文件大小。


場景,公司的一個小型項目,需同時支持移動端和PC端。最開始考慮做兩個獨立的項目。但后來考慮到總共只有4個功能頁面,布署起來相對麻煩。所以決定做在一個項目里。

1、升級vue-cli到4.x

npm install -g @vue/cli

2、項目創建

vue create multipage

項目配置不做描述,這里選了node_sass, babel, router, vuex

3、安裝element-ui和mint-ui

npm install element-ui
npm install mint-ui

4、配置按需引入。

借助 babel-plugin-component,我們可以只引入需要的組件,以達到打包項目體積的目的。

然后,將 .babelrc 修改為:

module.exports = {
  "presets": [
    '@vue/cli-plugin-babel/preset'
  ],
  "plugins": [
    [
      "component",
      {
        "libraryName": "mint-ui",
        "style": true
      },
      "mint-ui"
    ],
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk",
        "style": true
      },
      "element-ui"
    ],
  ]
}

5、安裝axios

npm install axios

6、新建移動端和PC端模板頁面。

移動端:public/mobile.html

pc端:public/pc.html

7、刪除多余目錄和文件,新建移動端目錄(src/mobile)和PC端目錄(src/pc)

新建移動端入口頁(src/mobile/main.js)和首頁(src/mobile/index.vue)

8、新建vue.config.js,添加多頁面設置:

module.exports = {
    pages: {
        mobile: {
            // page 的入口
            entry: "src/mobile/main.js",
            // 模板來源
            template: "public/mobile.html",
            // 在 dist/index.html 的輸出
            filename: "mobile/index.html",
            // 當使用 title 選項時,
            // template 中的 title 標簽需要是 <title><%= htmlWebpackPlugin.options.title %></title>
            title: "Index Page",
            // 在這個頁面中包含的塊,默認情況下會包含
            // 提取出來的通用 chunk 和 vendor chunk。
            chunks: ["chunk-vendors", "chunk-common", "mobile"]
        },
        pc: {
            // page 的入口
            entry: "src/pc/main.js",
            // 模板來源
            template: "public/pc.html",
            // 在 dist/index.html 的輸出
            filename: "pc/index.html",
            // 當使用 title 選項時,
            // template 中的 title 標簽需要是 <title><%= htmlWebpackPlugin.options.title %></title>
            title: "Index Page",
            // 在這個頁面中包含的塊,默認情況下會包含
            // 提取出來的通用 chunk 和 vendor chunk。
            chunks: ["chunk-vendors", "chunk-common", "pc"]
        },
    }
}

9、查看打包大小:

npm run build

可以看到chunk-vendors.xxx.js大小只有164.32kiB,如果mobile.xxx.js和mobile_index.js做得好,整個項目首次加載應該是超快的。

10、運行項目

npm run serve

提示如下:

App running at:
- Local: http://localhost:8080/
- Network: http://192.168.2.182:8080/

移動端訪問方法:http://localhost:8080/mobile/

PC端訪問方法:http://localhost:8080/pc/

以上路徑可以在vue.config.js中修改。

全劇終。

代碼可以在以下地址可以下載:

https://github.com/gavinjzx/multipage


免責聲明!

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



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