Skip to content
Jack Lo edited this page Jan 10, 2019 · 1 revision

wxs是用于wxml中的config和utils的集合。

一般来说,如果不特别处理的话,我们在引用资源的时候会将完整路径都书写,开发阶段使用本地静态服务器资源:

<image src="http://localhost:8080/static/img/avt.jpg" />

当我们需要上线的时候,我们需要切换到线上cdn资源:

<image src="https://cdn.jack-lo.com/static/img/avt.jpg" />

但是页面一多起来,这样就切换就显得十分困难。

使用wxs可以解决这个问题,首先我们创建一个公共的wxs文件client/wxs/index.wxs,并做如下定义:

var cdnPath = 'http://localhost:8080/static';

module.exports = {
  cdnPath: cdnPath,
};

我们在页面中这样拼接资源链接:

<wxs src="../../wxs/index.wxs" module="utils"></wxs>
<image src="{{utils.cdnPath}}/img/avt.jpg" />

这样我们上线的时候只需要对应修改一下client/wxs/index.wxscdnPath的值为https://cdn.jack-lo.com/static就可以了。

为了方便使用,我们内置了cdnPathTable.wxs,在将不同环境预设好之后,只需要在client/wxs/index.wxs中切换就可以了:

var cdnPathTable = require('./cdnPathTable.wxs');

var cdnPath = cdnPathTable.local;
// var cdnPath = cdnPathTable.dev;
// var cdnPath = cdnPathTable.release;

module.exports = {
  cdnPath: cdnPath,
};

后话

既然wxs的设计等于config+utils,那为什么不直接使用config和utils就好了,这样维护起来更方便?

答案是,可以,但是麻烦,由于wxs的功能并不完全对等javascript,所以很难达到通用,具体可以查看微信小程序开发文档关于wxs的介绍。

还有重要的一点是,wxs在wxml中比javascript通用,它可以直接在template里引用。

举个例子,假如我们的cdnPath是定义在config中的,那么我们的使用将是这样的:

const { config } = require('../../framework/index.js');

Page({
  data: {
    cdnPath: config.cdnPath,
  },
});

挂载到data之后,才能在wxml上使用:

<image src="{{cdnPath}}/img/avt.jpg" />

这样等效于我们使用wxs,但是,如果你使用了template,那这个过程就会变得麻烦且冗余了:

<template name="tpl">
  <image src="{{cdnPath}}/img/logo.jpg" />
</template>

<template is="tpl" data="{{ cdnPath }}" />
<image src="{{cdnPath}}/img/avt.jpg" />

可以看到,即便cdnPath已经在data里挂载了,你还是需要手动传给tempalte,而使用wxs则不需要:

<wxs src="../../wxs/index.wxs" module="utils"></wxs>

<template name="tpl">
  <image src="{{utils.cdnPath}}/img/logo.jpg" />
</template>

<template is="tpl" />
<image src="{{utils.cdnPath}}/img/avt.jpg" />

这样的场景多了之后,你就会发现每次挂载data再手动传template确实是挺麻烦的事情。

Clone this wiki locally