# modularity

It is possible to extract some common code into a separate js File, as a module. Modules are only available through the module.exports or exports To expose the interface.

Note:

  • exports yes module.exports So you can change it at will inside the module exports This will cause unknown errors. Therefore, it is more recommended that developers adopt module.exports To expose the module interface, unless you already know the relationship between the two.
  • Small programs do not currently support the direct introduction of Node_modules , Developers need to use Node_modules It is recommended to copy the relevant code to the Mini Program directory, or use the Mini Program support npm Function.
// common.js
function sayHello(Name) {
  console.log(`Hello ${name} !`)
}
function sayGoodbye(Name) {
  console.log(`Goodbye ${name} !`)
}

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

In files that need to use these modules, use the Require Introducing Public Code

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

# File scope

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

By globalfunctions getApp You can get the global application instance, if you need the global data can be found in the App() In settings such as:

// 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 it run Before b.js,  now the globalData shoule be 2.
console.log(getApp().globalData)