博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
module.exports小程序模块化,require
阅读量:4538 次
发布时间:2019-06-08

本文共 1782 字,大约阅读时间需要 5 分钟。

小程序模块化

可以将一些公共的代码抽离成为一个单独的 js 文件,作为一个模块。模块只有通过 module.exports 或者 exports 才能对外暴露接口。

tips:exports 是 module.exports 的一个引用,因此在模块里边随意更改 exports 的指向会造成未知的错误。所以更推荐开发者采用 module.exports 来暴露模块接口,除非你已经清晰知道这两者的关系。

// common.jsfunction sayHello(name) {  console.log(`Hello ${name} !`)}function sayGoodbye(name) {  console.log(`Goodbye ${name} !`)}module.exports.sayHello = sayHelloexports.sayGoodbye = sayGoodbye

在需要使用这些模块的文件中,使用 require(path) 将公共代码引入

const common = require('common.js')Page({  helloMINA() {    common.sayHello('MINA')  },  goodbyeMINA() {    common.sayGoodbye('MINA')  }})

tips:require 暂时不支持绝对路径。

封装!!!

var project = 'm';        //项目var apiHost = 'https://xxx.com/'+project;     //接口地址var apiList = {     "userInfo": "/User/userInfo",};function getData(cmd, data, cb) {     if (cmd in apiList) {          var new_cmd = apiList[cmd];          var hosts = apiHost + new_cmd;          wx.request({               url: hosts,               data: data,               method: data.method ? data.method : 'GET',               header: {                    "Content-Type": "application/x-www-form-urlencoded"               },               success: function(res) {                    typeof cb == 'function' && cb(res.data);               },               fail: function() {                    console.log('网络请求失败');               }          });     } else {          return false;     }}// 抛出module.exports = {     getData: getData,}

引入

// 相对路径var getData = require('../../utils/getData.js');

使用

getData.getData('userInfo', {     openid: app.globalData.openid,     method: "POST"}, function(data) {     if (!data.errno) {          that.setData({               userInfo: data.userInfo,          })     } else {         // 提示     }})

转载于:https://www.cnblogs.com/jiqing9006/p/10542483.html

你可能感兴趣的文章
linux64需要增加的依赖库
查看>>
手机网站页面模板
查看>>
Huffman树与编码的简单实现
查看>>
__delattr__\__delitem__
查看>>
htmlunit简单百度搜索,网页解析
查看>>
Cocos2dx Android在编译的时候格式出错例如(snprintf)
查看>>
spring不同环境下用不同的配置文件
查看>>
数组_leetcode80
查看>>
SQL Error (1130): Host '192.168.1.100' is not allowed to connect to this MySQL server
查看>>
普通线程类获取service,controller等spring容器类
查看>>
Redis高级实践之————Redis短连接性能优化
查看>>
ThreadLocal使用
查看>>
POJ - 2155 Matrix(二维树状数组)
查看>>
基于Cat的分布式调用追踪
查看>>
建筑物联动
查看>>
汇编语言 手记5
查看>>
牛客网暑期ACM多校训练营(第三场) E-Sort String next数组的应用
查看>>
如何成功的捕捉一只女神
查看>>
有关HTTP的粗读
查看>>
连接mysql数据库,创建用户模型
查看>>