Modularization

Some common codes can be extracted to create an independent js file as a module. APIs for the module can be exposed only via module.exports or exports.

Note:

  • exports is a reference to module.exports. Therefore, a random modification to the point of exports in the module may cause an unknown error. Developers are advised to expose module APIs via module.exports if they do not know the relationship between them.
  • Currently, node_modules cannot be directly passed into Mini Programs. To use node_modules, developers are advised to copy relevant code to the directory of the Mini Program, or use the npm feature supported by Mini Programs.
// common.js
function sayHello(name) {
  console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
  console.log(`Goodbye ${name} !`)
}

module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye

To pass common code into files that need to access these modules, use require.

var common = require('common.js')
Page({
  helloMINA: function() {
    common.sayHello('MINA')
  },
  goodbyeMINA: function() {
    common.sayGoodbye('MINA')
  }
})

File Scope

Variables and functions declared in the JavaScript file are valid only in the file. Variables and functions with the same names can be declared in different files without affecting each other.

The global application instance can be obtained via the global function getApp. To obtain the global data, you can set App(). For example:

//app.js
App({
  globalData: 1
})
// a.js
// The localValue can only be used in file a.js.
var localValue = 'a'
// Get the app instance.
var app = getApp()
// Get the global data and change it.
app.globalData++
// b.js
// You can redefine localValue in file b.js, without interference with the localValue in a.js.
var localValue = 'b'
// If a.js is run before b.js, now the globalData should be 2.
console.log(getApp().globalData)