官网理论
模块化
可以将一些公共的代码抽离成为一个单独的 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(path) 将公共代码引入
const common = require('common.js')
Page({
helloMINA() {
common.sayHello('MINA')
},
goodbyeMINA() {
common.sayGoodbye('MINA')
}
})
参考来自官网 框架->模块化
来源:https://www.cnblogs.com/zhihou/p/10204203.html