一 概述
- 可以将一些公共的代码抽离成为一个单独的 js 文件,作为一个模块
- 模块只有通过
module.exports
或者exports
才能对外暴露接口 - 在需要使用这些模块的文件中,使用
require
将公共代码引入
二 模块化
2.1 定义模块
创建utils文件夹,并在utils文件夹下创建common.js
文件
模块定义方式一
function sayHello(name) {
console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
console.log(`Goodbye ${name} !`)
}
module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye
exports.name="Lucy"
exports.age=18
模块定义方式二
module.exports = {
name: "Lucy",
age:18,
sayHello(name) {
console.log(`Hello ${name} !`)
},
sayGoodbye(name) {
console.log(`Goodbye ${name} !`)
}
}
2.2 使用模块(index page)
index.wxml
<text>{{name}}——{{age}}</text>
index.js
var common=require('../utils/common')
Page({
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
common.sayHello(common.name)
common.sayGoodbye(common.name)
this.setData({
name:common.name,
age:common.age
})
},
})
2.3 效果图
小程序显示 | console控制台 |
---|---|
![]() | ![]() |