小白教程

 找回密码
 立即注册

微信小程序 模块化

发布者: 小白教程

模块化

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

注意:

  • exports 是 module.exports 的一个引用,因此在模块里边随意更改 exports 的指向会造成未知的错误。所以更推荐开发者采用 module.exports 来暴露模块接口,除非你已经清晰知道这两者的关系。
  • 小程序目前不支持直接引入 node_modules , 开发者需要使用到 node_modules 时候建议拷贝出相关的代码到小程序的目录中,或者使用小程序支持的 npm 功能。
// common.js
function sayHello(name) {
  console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
  console.log(`Goodbye ${name} !`)
}

module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye

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

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

文件作用域

在 JavaScript 文件中声明的变量和函数只在该文件中有效;不同的文件中可以声明相同名字的变量和函数,不会互相影响。

通过全局函数 getApp 可以获取全局的应用实例,如果需要全局的数据可以在 App() 中设置,如:

// app.js
App({
  globalData: 1
})
// a.js
// The localValue can only be used in file a.js.
var localValue = 'a'
// Get the app instance.
var app = getApp()
// Get the global data and change it.
app.globalData++
// b.js
// You can redefine localValue in file b.js, without interference with the localValue in a.js.
var localValue = 'b'
// If a.js it run before b.js, now the globalData shoule be 2.
console.log(getApp().globalData)



下节更精彩
微信小程序教程
  1. 微信小程序 小程序简介

  2. 微信小程序 开始

  3. 小程序代码构成

  4. 小程序宿主环境

  5. 小程序协同工作和发布

  6. 配置小程序

  7. sitemap配置

  8. 微信小程序 场景值

  9. 微信小程序 注册小程序

  10. 微信小程序 注册页面

  11. 微信小程序 页面生命周期

  12. 微信小程序 页面路由

  13. 微信小程序 模块化

  14. 微信小程序 API

  15. 微信小程序 WXML

  16. 微信小程序 WXSS

  17. 微信小程序 WXS

  18. 微信小程序 事件系统

  19. 微信小程序 简单双向绑定

  20. 微信小程序 基础组件

  21. 微信小程序 获取界面上的节点信息

  22. 微信小程序 响应显示区域变化

  23. 微信小程序 动画

  24. 微信小程序 初始渲染缓存

  25. 微信小程序 运行环境

  26. 微信小程序 JavaScript支持情况

  27. 微信小程序 运行机制

  28. 微信小程序 更新机制

  29. 微信小程序 组件模板和样式

  30. 微信小程序 Component构造器

  31. 微信小程序 组件间通信与时间

  32. 微信小程序 组件生命周期

  33. 微信小程序 behaviors

  34. 微信小程序 组件间关系

  35. 微信小程序 数据监听器

  36. 微信小程序 纯数据字段

  37. 微信小程序 抽象节点

  38. 微信小程序 自定义组件扩展

  39. 微信小程序 开发第三方自定义组件

  40. 微信小程序 单元测试

  41. 微信小程序 开发插件

  42. 微信小程序 使用插件

  43. 微信小程序 插件调用API的限制

  44. 微信小程序 插件功能页

  45. 微信小程序 网络

  46. 微信小程序 文件系统

  47. 微信小程序 画布

  48. 微信小程序 分包加载

  49. 微信小程序 多线程Worker

  50. 微信小程序 服务端能力

  51. 微信小程序 自定义tabBar

  52. 微信小程序 周期性更新

  53. 微信小程序 数据预拉取

  54. 微信小程序 DarkMode适配指南

  55. 微信小程序 大屏适配指南

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 06:15 , Processed in 0.022870 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部