21

webpack重构小程序开发

 5 years ago
source link: http://www.ajiehome.com/shi-yong-webpackda-bao-xiao-cheng-xu-kai-fa/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

小程序开发痛点

编写模板时通常是以下这种语法:

<!--index.wxml-->
<view class="container">
  <view class="userinfo">
    <button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
  </view>
</view>

这个时候希望在写标签的时候能支持一套语法,比如根据标签的缩进关系来决定dom的嵌套层次:

view.container
	view.userinfo(bindgetuserinfo='getUserInfo' open-type='getUserInfo')
		button
		image.userinfo-avatar
		text.userinfo-nickname {{userInfo.nickName}}
	view.usermotto
		text.user-motto {{motto}}

这就是我们熟悉的pug语法编写的dom结构,但小程序是不识别这种语法的,我们需要将这段模板编译成小程序希望的.wxml这种格式。

sass,less, postCss等css预处理工具的出现,为前端编写css样式带来了巨大的遍历,将他们引入到小程序的开发中带来的优点也是显而易见的。

解决方案:借鉴vue

<template lang="pug">
    // 模板内容
</template>
<script>
	// 脚本内容
</script>
<style lang="sass">
    // 样式内容
</style>

这就是我们所期望的开发小程序的开发模式:

1、dom, 脚本,样式写到同一个文件

2、通过指定模板引擎来构建更简洁的dom结构

3、通过引入css预处理工具提升css编写效率

如何实现

要实现上述一系列的任务,大体上的流程是这样的:首先启动一个task任务,确定需要被编译的文件的路径和输出文件的路径,即遍历pages下面像index,logs这样一个又一个的页面,然后对每个页面后缀名.mina的文件进行词法的分析,从里面抽取到template、脚本和样式,分别对应这三类文件进行相应的plugin的操作:template使用pug进行编译,脚本的话使用了一些新语法比如async,await,需要进行babel编译,样式文件的话,使用sass-loader插件进行编译。等上述编译完成后的内容输出到指定的文件夹下面。

将模板样式脚本抽离到单独文件的中间件就是我们的loader


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK