Vue-cli3 多页面分析

实现思路: 根据url的地址进行匹配对应的单页面模块,注册对应的router和store。
路由地址:http://localhost:8111/module/activety.html?#/engine

项目结构说明

├── dist // 打包后目录
│ ├── favicon.ico
│ ├── module // 每个模块的入口页面
│ │ ├── activity-calendar.html
│ │ ├── activity-engine.html
│ │ ...
│ │ └── welfare-activity.html
│ ├── module.zip
│ ├── static // 静态资源
│ │ ├── cordova
│ │ ├── css
│ │ ├── img
│ │ ├── init-activity.min.js
│ │ ├── init.js
│ │ ├── js
│ │ ├── jsBridge
│ │ ├── media
│ │ └── svga
│ └── static.zip
├── hooks // JS脚本
│ ├── checkcommitmsg.js
│ ├── checkdistfilesize.js
│ ├── checkfilesize.js
│ └── config.js
├── public // 公共资源直接拷贝到dist
│ ├── favicon.ico
│ ├── index.html
│ └── static
│ ├── cordova // 与原生交互的插件库
│ ├── img
│ ├── init-activity.min.js
│ ├── init.js
│ ├── jsBridge // 注册全局方法,H5与原生的交互方法
│ └── svga
├── src
│ ├── api
│ │ └── index.js
│ ├── assets
│ │ ├── area.json
│ │ └── img
│ ├── components // 公有组件
│ │ ├── app-actionSheet.vue
│ │ ├── app-alert
│ │ ...
│ │ ├── app-upLoad.vue
│ │ └── rule.vue
│ ├── config // 环境配置
│ │ ├── env.js
│ │ └── index.js
│ ├── lib
│ │ ├── checker.js
│ │ └── report.js
│ ├── main.js
│ ├── module // 每个模块都是单页面的一套,main.js复用顶级入口main.js
│ │ ├── activity-calendar
│ │ │ ├── api
│ │ │ ├── app.vue
│ │ │ ├── css
│ │ │ ├── img
│ │ │ ├── main.js
│ │ │ ├── page.vue
│ │ │ ├── router
│ │ │ ├── service
│ │ │ ├── store
│ │ │ └── view
│ │ ├── sign-con
│ │ └── welfare-activity
│ ├── request
│ │ ├── axios-jsonp.js
│ │ ├── checkTimeout.js
│ │ ├── index.js
│ │ ├── interceptors-changeOrigin.js
│ │ └── interceptors-common.js
│ ├── router // 匹配模块,加载模块中的路由
│ │ └── index.js
│ ├── store // 匹配模块,注册模块中的store进行合并
│ │ ├── actions.js
│ │ ├── getters.js
│ │ ├── index.js
│ │ ├── mutation-types.js
│ │ ├── mutations.js
│ │ ├── plugins
│ │ └── state.js
│ ├── styles
│ │ ├── index.scss
│ │ ├── reset.scss
│ └── utils
│ ├── ajax.js
│ ├── checker.js
│ ├── coInfo.js
│ ├── common.js
│ ├── getQuery.js
│ ├── global.js
│ ├── log.js
│ ├── md5.js
│ ├── native.js // 调用原生的全局方法
│ ├── pageUrl.js
│ ├── timeFilter.js
│ ├── util.js
│ ├── wxAuth.js
│ ├── wxAuthDefault.js
│ ├── wxAuthorization.js // 微信授权
│ ├── wxAuthorizeUrl.js
│ └── wxSetSecondShare.js
├── README.md
├── babel.config.js
├── package.json
├── deploy.js // 代码部署脚本,包含登录和文件上传至服务器
├── titlemapper.js // 每个模块对应的title(内嵌网页可不用)
└── vue.config.js

webpack 的打包配置vue.config.js

const path = require('path')
const glob = require('glob')
const titlemapper = require('./titlemapper')
const FileManagerPlugin = require('filemanager-webpack-plugin')

var buildConfig = {
  outputDir: path.join(__dirname, './dist'),
  publicPath: process.env.NODE_ENV === 'production' ? '../' : '/',
  assetsDir: 'static/'
}

// 配置pages多页面获取当前文件夹下的html和js
function getEntry(globPath) {
  let entries = {}, pageName
  glob.sync(globPath).forEach(function(entry) {
    pageName = entry.split('/').pop()
    entries[pageName] = {
      entry: `src/module/${pageName}/main.js`,   // 入口js
      template: 'public/index.html',                        // 入口模板
      title: titlemapper[pageName] || '同学会',       // 页面title
      filename: `module/${pageName}.html`        // 打包后的文件名
    }
  })
  return entries
}
const pages = getEntry('./src/module/**?')
let configureWebpack = {}
// 如果是打包,则加上打包压缩的插件
if (process.env.NODE_ENV === 'production') {
  configureWebpack = {
    output: {
      path: buildConfig.outputDir,
      publicPath: buildConfig.publicPath,
      filename: buildConfig.assetsDir + 'js/[name].[contenthash:8].js'
    },
    plugins: [
      new FileManagerPlugin({         // 初始化filemanager-webpack-plugin 插件实例
        onStart: {
          delete: [ // 首先需要删除项目根目录下的dist.zip
            './dist'
          ]
        },
        onEnd: {
          // 为了解决基本当前目录压缩的问题
          copy: [
            { source: './dist/module', destination: './dist/moduleCopy/module' },
            { source: './dist/static', destination: './dist/staticCopy/static' }
          ],
          archive: [ // 然后我们选择dist文件夹将之打包成dist.zip并放在根目录
            // { source: './dist/module', destination: './dist/module.zip' },
            { source: './dist/staticCopy', destination: './dist/static.zip' },
            { source: './dist/moduleCopy', destination: './dist/module.zip' }
          ],
          delete: ['./dist/moduleCopy', './dist/staticCopy']
        }
      })
    ]
  }
}
// 配置
module.exports = {
  publicPath: buildConfig.publicPath,
  productionSourceMap: false,
  outputDir: buildConfig.outputDir,
  assetsDir: buildConfig.assetsDir,
  pages,
  devServer: {
    index: 'index.html',                           // 默认启动serve 打开index页面
    open: process.platform === 'darwin',
    host: '0.0.0.0',
    port: 8111,
    https: false,
    proxy: null, // 设置代理
    // before: app => {}
    disableHostCheck: true              // 禁用webpack热重载检查 解决热更新失效问题
  },

  // css相关配置
  css: {
    extract: true, // 是否使用css分离插件 ExtractTextPlugin
    sourceMap: false, // 开启 CSS source maps?
    loaderOptions: {
      // less: {
      //   javascriptEnabled: true
      // }
      sass: {
        implementation: require('sass') // This line must in sass option
      }
    }, // css预设器配置项
    modules: false // 启用 CSS modules for all css / pre-processor files.
  },

  // 是否为 Babel 或 TypeScript 使用 thread-loader。该选项在系统的 CPU 有多于一个内核时自动启用,仅作用于生产构建。
  parallel: require('os').cpus().length > 1,
  chainWebpack: config => {
    config.module
      .rule('images')
      .use('url-loader')
      .loader('url-loader')
      .tap(options => {
        // 修改它的选项...
        options.limit = 100
        return options
      })
    config.module
      .rule('worker')
      .test(/\.worker\.js$/)
      .use('worker-loader').loader('worker-loader')
      .options({
        inline: true,
        fallback: false
      }).end()
    config.resolve.alias
      .set('@', path.resolve('src'))
      .set('api', path.resolve('src/api'))
      .set('assets', path.resolve('src/assets'))
      .set('components', path.resolve('src/components'))
      .set('config', path.resolve('src/config'))
      .set('request', path.resolve('src/request'))
      .set('module', path.resolve('src/module'))
      .set('styles', path.resolve('src/styles'))
      .set('utils', path.resolve('src/utils'))
      .set('lib', path.resolve('src/lib'))

    Object.keys(pages).forEach(entryName => {
      config.plugins.delete(`prefetch-${entryName}`)
    })
    if (process.env.NODE_ENV === 'production') {
      config.plugin('extract-css').tap(() => [{
        path: buildConfig.outputDir,
        filename: buildConfig.assetsDir + 'css/[name].[contenthash:8].css'
      }])
    }
  },
  configureWebpack: configureWebpack
}

多页面main.js

主入口main.js:根据路由匹配当前模块的根组件(app.vue), 然后进行创建vue 实例。
模块入口main.js:直接引用主入口main.js,特别情况可单独写

try {
  moduleApp = require('module/' + MODULE_NAME + '/app').default
} catch (e) {
  console.error('require module app error', e)
}

// 创建和挂载根实例
new Vue({
  router,
  store,
  render: h => h(moduleApp)
}).$mount('#app')

多页面Store

主要借助store的属性modules来实现,项目store可分为主入口的公有store和模块的store,根据路由匹配当前模块的store, 然后进行合并。

/**
 * @store(vuex)主入口
 */
import Vue from 'vue'
import Vuex from 'vuex'
import {MODULE_NAME} from 'config/index'
import state from './state'
import mutations from './mutations'
import * as actions from './actions'
import * as getters from './getters'
// import plugins from './plugins/plugin-logger'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
const store = new Vuex.Store({
  modules: {
    common: {
      state,
      mutations,
      actions,
      getters
    }
  },
  strict: debug
  // plugins
})
/**
 * 只加载当前模块的store数据
 */
try {
  store.registerModule(`page_${MODULE_NAME}`, require('module/' + MODULE_NAME + '/store/index').default)
} catch (e) {
  console.error('require module store error', e)
}
export default store

多页面路由Router

据路由匹配当前模块的router, 然后创建路由。

import Vue from 'vue'
import VueRouter from 'vue-router'
import { MODULE_NAME } from 'config/index'
import store from '@/store'
import Native from 'utils/native'
let moduleRouter = null
try {
  moduleRouter = require('module/' + MODULE_NAME + '/router/index.js').default
} catch (e) {
  console.error('require module router error', e)
}
Vue.use(VueRouter)
const router = new VueRouter({
  // hash、abstract、history
  mode: 'hash',
  routes: [
    moduleRouter
  ]
})

/**
 * 全局钩子
 * @param {Object} to 目标路由
 * @param {Object} from 当前路由
 * @param {Function} next 回调函数
 */
router.beforeEach((to, from, next) => {
  store.dispatch('updatePageLoadingStatus', { pageLoadCompleted: false })
  next()
})

router.afterEach(function(to) {
  Native.loadCompleted({}, (data) => {
    console.log('Native.loadCompleted success', data, to)
  }, (data) => {
    console.error('Native.loadCompleted error', data)
  })
  store.dispatch('updatePageLoadingStatus', { pageLoadCompleted: true })
})
export default router
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335