微信小程序筆記<六>模塊化 —— module.exports

微信小程序中全部 js 文件做用域皆爲獨立的,每個 js 文件即爲一個模塊。模塊與模塊之間的引用經過 module.exports 或 exports 對外暴露接口。node

注意:小程序

  • 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 暫不支持絕對路徑。微信小程序

相關文章
相關標籤/搜索