Lucas Liao's Blog

pc/mobile端入口兼容方案

缘起

最近接触到某省人民医院官网项目,要求适配PC/移动端,因为后台数据接口是同一套,创建两个独立代码仓库的话不方便维护,因此在原来开发基础上,通过修改webpack打包配置,完成前端multiple phatform开发环境的搭建。

配置思路

webpack打包后,浏览器加载index.html,index.html可以理解为一个代理入口(中间商),在此判断当前浏览器设备属于pc端,还是mobile端,然后重定向对应程序入口html文件。

封装方法读取入口文件

glob是webpack安装时依赖的一个第三方模块,该模块允许你使用等符号,例如lib/.js就是获取lib文件夹下的所有js后缀名的文件

1
2
3
4
5
6
7
8
9
10
exports.entries = function () {
var entryFiles = glob.sync(PAGE_PATH + '/*/*.js')
var map = {}
entryFiles.forEach((filePath) => {
var filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'))
map[filename] = filePath
})
return map
}

PAGE_PATH为入口文件夹名称,如你的入口文件放到platform/main/aa.js, platform/pc/bb.js, 则PAGE_PATH为platform。

如本项目中,我的入口文件分别设置为:

  • 主入口 => /platform/index/index.html
  • pc浏览器入口 => /platform/pc/p_index.html
  • mobile浏览器入口 => /platform/mobile/m_index.html

路由配置及重定向

针对两个平台,建立相应的路由表。

在路由beforeEach生命周期中,可以通过正则判断当前浏览器设备,重定向到相应平台路由。

1
2
3
4
5
6
7
router.beforeEach((to, from, next) => {
if (!/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
window.location.href = '/page/pc/p_index.html#/'
return
}
next()
})

同时,在主入口的html文件中加上如下的js脚本, 用于首次进入判断当前浏览器设备。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script>
function isMobile () {
var userAgenInfo = navigator.userAgent
var Agents = new Array('Android', 'iPhone', 'SymbianOS', 'iPad', 'iPod')
var flag = false
for (var v = 0; v < Agents.length; v++) {
if (userAgenInfo.indexOf(Agents[v]) > 0) {
flag = true
break
}
}
return flag
}
if (isMobile()) {
window.location.href = '/page/pc/m_index.html#/'
} else {
window.location.href = '/page/pc/p_index.html#/'
}
</script>

其他实现

本实践主要由前端来配置url跳转,其实后端通过配置nginx, 转发url,这样会更加灵活而且更加优雅,有兴趣可以了解一下。

1
2
3
4
5
6
7
8
9
10
11
12
server {
listen 80;
server_name fe.sherlocked93.club;

location / {
root /usr/share/nginx/html/pc;
if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
root /usr/share/nginx/html/mobile;
}
index index.html;
}
}

本项目demo github传送门:https://github.com/yiyu-liao/pc-mobile-frame