微信小程序笔记<六>模块化 —— module.exports


微信小程序中所有 js 文件作用域皆为独立的,每一个 js 文件即为一个模块。模块与模块之间的引用通过 module.exports 或 exports 对外暴露接口。

注意:

  • exports 是 module.exports 的一个引用,因此在模块里边随意更改 exports 的指向会造成未知的错误。( 官方推荐使用 module.exports 来暴露模块接口 )
  • 小程序目前不支持直接引入 node_modules , 开发者需要使用到 node_modules 时候建议拷贝出相关的代码到小程序的目录中。
// common/tool.js ===============================
function Hello(){
  console.log("say hello!");
}
function sayHi(){
  console.log("Hi! I'm mirage. how are you");
}
module.exports.Hello = Hello;
exports.sayHi = sayHi;

// index/index.js ===============================
var tool = require("../common/tool.js");
Page({
  onLoad:function(){
    tool.Hello(); // 输出  say hello!
    tool.sayHi(); // 输出  Hi! I'm mirage. how are you
})

引用模块也是 require(path) 官方注明:require 暂不支持绝对路径。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM