GitHub主页:https://github.com/452MJ/weex-multi-page-demo
前言
weex是一个跨平台开发框架,奉行“一次编写,三端运行”的理念,不过一般公司用weex开发APP为主,如果要在web端开发一个网页,相信还是会以Vue作为首选。不过由于公司之前的APP项目就已经封装了部分公共component及一些工具类库。所以我首选用weex来做公众号H5网页开发。
查阅相关资料,比如官方demo weex-hackernews,是一个SPA单页面应用。需要引入vue-router、vuex等库。
SPA痛点
1.对于vuex中store的数据管理过于复杂,不利于代码解耦;2.由于需要跳转公众号文章,所以返回时,vue-router会重置,导致需要自己适配每个返回页,过程十分繁琐;3.初次加载的js文件太大,页面加载太慢
解决思路
动手修改webpack配置,把每个页面模块都单独配置成index.html+index.js,把一个大SPA切割成若干个小SPA,每个HTML单独加载对应的js文件,以达到多页面效果。
手把手演示
weexpack create weex-multi-page-demo


然后我们执行npm install(PS:请务必在Terminal终端下输入执行)
npm install
安装所需要的依赖库,最后得到相应的node_modules
我们先看看直接编译出来的js文件是如何的,我们执行npm run build
npm run build
出现一个/dist文件夹,里面放的就是我们编写的.vue文件后run build后对应的的js文件

接着执行npm run serve看看具体的效果
npm run serve

现在我们想配置出对应的html文件,就需要着手修改webpack,我们打开wevpack.config.js

要自动生成.html文件,我们需要用到webpack的一个plugin插件,html-webpack-plugin。引入插件后代码如图

每当我们需要生成一个.html文件,都需要往plugins中添加一个html-webpack-plugin,所以记得用let来定义plugins。
Weex的工程是通过webpack.config.js中的walk方法来遍历src文件夹中的.vue文件,我们可以通过对walk()进行修改,在遍历.vue文件的同时,添加对应的html-webpack-plugin,未作修改前的walk()方法如图

可以看到,当检索到.vue文件的时候,就会往entry中新增一个对象,同理我们可以在检索到.vue文件的时候便往plugins中新增一个html-webpack-plugin

其中用到的模板template.html 如图

然后我们npm run build
npm run build

生成的.html中多了一行代码

初步见成果,url中已经看不到单页面的#了,是一个独立的html页面

然后我们又一次添加多个不同的页面试试



可以看到html-webpack-plugin的配置还不完善,导致模板生成的.html把所有.js都引用了,且.html的命名与.vue的命名相关联,比如ccc.vue生成的便是ccc.html。接下来我们再优化一下html-webpack-plugin的配置,修改如下

chunks 选项的作用主要是针对多入口(entry)文件。当你有多个入口文件的时候,对应就会生成多个编译后的 js 文件。那么 chunks 选项就可以决定是否都使用这些生成的 js 文件。
然后我们再npm run build一遍,看看生成的.html文件

可以看到三个不同的页面都引用自己的.js文件
接下来我们再优化一下,比如说,每个页面模块我只想index.vue才生成index.html,ccc.vue则不生成html。那我们应该如何写呢?很简单,如图

npm run build后

可以看到c页面中没有index.vue,所以不会生成对应的.html
最后我们对webConfig配置,不生成xx.web.js文件

最终的dist文件夹内容如下

接下来我们就可以直接通过url的形式来访问a页面与b页面,无需通过配置复杂的的vue-router,无需绑定vuex来管理数据


至此,一个简单的weex的webpack多页面配置已经分析完成。
不足的地方
因为template.html的公共引用库的原因
<script src='../../../node_modules/vue/dist/vue.runtime.min.js'></script>
所以每个页面都必须写成/src/page/xx/index.vue(后面发现只要引用cdn上的js就可以去掉丑陋的../../../了)
<script src='https://cdn.jsdeivr.net/npm/vue@2.4.3/dist/vue.runtime.min.js'></script>
网友评论