# modularity

You can extract some common code into a separate js file, as a module.Modules can only be obtained by module.exports Orexportsto expose the interface.

NOTE:

  • Exportsare module.exports Therefore, changing the reference toexportsin the module will cause an unknown error.Therefore, it is recommended that developers usemodule.exportsto expose the module interface, unless you have a clear understanding of the relationship between the two.
  • Weixin Mini Program Direct introduction ofnode_modulesis not currently supported, Developers need to usenode_moduleswhen it is recommended to copy the relevant code into the Mini Program's directory, or use the Mini Program-supported 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 require the use of these modules, usingrequireto introduce common code

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

# File scope

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

A global instance of an application can be obtained through the global functiongetApp. If you need global data, you can set it inApp (]], 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)