微信小程序开发模块化
作者: --时间: 2022-09-29
阅读量:
微信小程序模块化
在小程序中,采用模块化的编程方式可以更好地组织代码结构,提高代码复用率和可维护性。
1. 抽离公共代码
将一些常用的函数或者变量抽离成为一个单独的 js 文件,作为一个模块,通过 module.exports 或者 exports 来对外暴露接口。
注意:
- exports 是 module.exports 的一个引用,如果在模块里边随意更改 exports 的指向会造成未知的错误。因此,建议开发者使用 module.exports 来暴露模块接口,除非你已经清晰知道这两者的关系。
- 小程序目前不支持直接引入 node_modules,如果需要使用到 node_modules 中的库,建议拷贝出相关的代码到小程序的目录中,或者使用小程序支持的 npm 功能。
以下是一个示例的 common.js 模块:
// common.js
function sayHello(name) {
console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
console.log(`Goodbye ${name} !`)
}
module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye
在需要使用这些模块的文件中,可以使用 require 来引入公共代码:
// index.js
var common = require('common.js')
Page({
onLoad: function() {
common.sayHello('world')
common.sayGoodbye('world')
}
})
2. 文件作用域
在 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)
上一篇:微信小程序开发页面路由
下一篇:微信小程序开发API

