## 模塊化
可以將一些公共的代碼抽離成為一個單獨的 js 文件,作為一個模塊。模塊只有通過?[module.exports](https://developers.weixin.qq.com/miniprogram/dev/reference/api/module.html)?或者?exports?才能對外暴露接口。
注意:
* exports?是?[module.exports](https://www.w3cschool.cn/weixinapp/weixinapp-gmub38qn.html)?的一個引用,因此在模塊里邊隨意更改?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')
}
})
~~~
### [](https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/module.html#%E6%96%87%E4%BB%B6%E4%BD%9C%E7%94%A8%E5%9F%9F)文件作用域
在 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)
~~~
- 惠惠軟件-開發自助學習系統
- 一.微信公眾號(服務號)申請流程
- 二.申請所需提前準備資料
- 三.認證微信公眾號:申請微信小程序流程
- 四.微信小程序安裝和開發環境
- 五.微信小程序如何上傳、提交審核、發布操作
- 六.微信小程序開發教程手冊
- 0.1微信小程序 小程序簡介
- 0.2微信小程序 開始第一步
- 0.3微信小程序 小程序代碼構成
- 0.4微信小程序 小程序宿主環境
- 0.5微信小程序 小程序協同工作和發布
- 0.6微信小程序 目錄結構
- 0.7微信小程序 全局配置
- 0.8微信小程序 頁面配置
- 0.9微信小程序 sitemap配置
- 0.10微信小程序 場景值
- 0.11微信小程序 注冊小程序
- 0.12微信小程序 注冊頁面
- 0.13微信小程序 頁面生命周期
- 0.14微信小程序 頁面路由
- 0.15微信小程序 模塊化
- 0.16微信小程序 API
- 0.17微信小程序 運行環境
- 0.18微信小程序 JavaScript支持情況
- 0.19微信小程序 運行機制
- 0.20微信小程序 更新機制
- 0.21微信小程序 廣告·Banner 廣告
- 0.22微信小程序 安全指引·開發原則與注意事項
- 0.23微信小程序 調試
- 0.24微信小程序 啟動性能
- 0.25微信小程序 運行時性能
- 0.26微信小程序 性能分析工具
- 0.27微信小程序 體驗評分
- 八.小程序的美工
- 8.1圖片大小
- 8.2顏色代碼
- 8.3小程序的美工技巧
- 九.微信小程序-定制開發
- 十.微信支付申請流程
- 十一.小程序支付對接流程
- 十二.微信小程序使用中常見問題匯總
- 十二.小程序開發中遇到的問題—匯總
- 十四.小程序問題及解決
- 十五.網站開發定制
- 1.開發定制流程
- 2.搭建網站的過程
- 3.做網站基本費用
- 4.服務器選什么系統更好?
- 十六.常用工具、軟件網站推薦