weex 入口搭建

  • Lanceloft
  • 10 Minutes
  • September 20, 2017

开头介绍

weex是阿里做的一套跨平台开发方案,用前端的知识来完成ios, android, web的应用, 在之前比较成熟的例子是react-native, 还有ionic也是用的人比较多的一套方案, react-native用的是react, ionic用的是angular, weex用的是vue. 在三种框架上来说vue是相对容易上手, 国内社区也比较成熟的一个, 门槛相对较低. 但是这并不代表weex在其余构建三端框架中占优势. 接触weex有一段时间,也构建过比较大型的应用, 就把一些心得进行分享一下.

搭建应用

weex有官方提供的一个脚手架 weex-toolkit
参考文档 https://weex.apache.org/cn/guide/tools/toolkit.html
官网介绍: weex-toolkit 是官方提供的一个脚手架命令行工具,你可以使用它进行 Weex 项目的创建,调试以及打包等功能。
还有一个比较完善的官网例子 weex-hacknews
https://github.com/weexteam/weex-hackernews

关于入口

用weex-toolkit构建应用和weex-hacknews在入口文件上是不一样的, 这里涉及了单页面应用和多页面应用的概念. 我们平时用vue, 普通的路由跳转, 实际上还是单页面应用, 在组件不进行销毁情况下, 原数据是可以保留, 同时在下一次跳转的时候是无需再次进行接口加载, css加载等. 而多页面实际是整个页面进行重载, 所有的接口, css等都是需要重新加载, 不保留一点之前的信息的. 就像html的a标签跳转和vue的路由跳转.
weex-toolkit的默认方法, 是把你写的每一个vue文件, 都当做一个新的入口文件, 所以在进行编译后, 会发现你写的有多少个vue, 就会打包出多少份bundle.js(具体概念可以查阅官网), 而weex-hacknews打包后会发现只会产生一个bundle.js文件 这里是因为入口文件的差异问题. weex-hacknews是只采用一个入口文件的方式, 所以一个入口再进入你写的vue文件, 所有的vue文件都通过这个入口文件进行打包.这里的修改在 webpack.config.js里面进行修改.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const weexConfig = {
entry: weexEntry,
output: {
path: pathTo.join(__dirname, 'dist'),
filename: '[name].js',
},
module: {
rules: [
{
test: /\.js$/,
use: [{
loader: 'babel-loader',
}],
exclude: /node_modules(?!\/.*(weex).*)/
},
{
test: /\.vue(\?[^?]+)?$/,
use: [{
loader: 'weex-loader'
}]
},
{
test: /\.we(\?[^?]+)?$/,
use: [{
loader: 'weex-loader'
}]
}
]
},
plugins: plugins,
};

这里只需要把entry进行修改为一个入口文件,就可以让所有的文件都通过这个入口文件进行加载. 只打包出一份bundle.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import App from './App.vue'
import router from './router'
import store from './store'
import { sync } from 'vuex-router-sync'
import * as filters from './filters'
import mixins from './mixins'

// sync the router with the vuex store.
// this registers `store.state.route`
sync(store, router)

// register global utility filters.
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key])
})

// register global mixins.
Vue.mixin(mixins)

// create the app instance.
// here we inject the router and store to all child components,
// making them available everywhere as `this.$router` and `this.$store`.
new Vue(Vue.util.extend({ el: '#root', router, store }, App))

if (weex.config.env.platform !== 'Web') {
router.push('/')
}

这里就是我的entry.js 文件的配置,也是有运用到vue-router和vuex

那么现在又产生了一个新的问题, 当把所有的文件都打包在一起的时候,虽然给开发提供了便利, 但是因为weex是普遍为了移动端, bundle.js 体积过大必然会导致加载时间的过长, 同时我试过打包一个空的页面, 因为weex框架的原因, 空的页面打包出来的体积也大约有60kb, 所以在搭建大型应用时候这个加载速度是比较蛋疼的. 我这里采取了另外的方法, 在主页面采取一个入口文件, 其余功能页面按功能划分入口文件的方法

1
2
3
4
5
6
entry: {
'index': path.resolve('src', 'entry.js'),
'home': path.resolve('src', './entrance/home.js'),
'mine': path.resolve('src', './entrance/mine.js'),
'general': path.resolve('src', './entrance/general.js'),
},

这样子按照功能划分, 就产生了四个入口, 四个入口文件互相并不关联, 而各自处理对应功能, 在加载时候只有到该功能才开始加载对应的bundle.js, 就可以讲原本体积较大的bundle.js分包为几个体积相对较小的文件, 加载速度是大大提高了.