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