Modularization

View Markdown

Last edited on 2026-08-10

Global Module

You can extract common code into a separate JS file and treat it as a module. A module can only expose interfaces externally through module.exports or exports.

Note:

  • exports is a reference to module.exports. Therefore, arbitrarily changing the pointer of exports within a module may cause unknown errors. It is not recommended to use both simultaneously unless you clearly understand the relationship between them.
  • Importing node_modules directly in Mini Program will not take effect. If you need to use it, please refer to the Build npm feature.
// common.js
function sayHello(name) {
 console.log(`Hello ${name}!`)
}
function sayGoodbye(name) {
 console.log(`Goodbye ${name}!`)
}

exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye

In files that need to use these modules, use require to import the 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 within that file. You can declare variables and functions with the same name in different files without them affecting each other.

// a.js
var localValue = 'a'
// b.js
var localValue = 'b'

The two localValue variables mentioned above are different variables.

Global Variables

If you want a variable to be used globally, you can export it using exports.

// common.js
exports.globalValue = 'c'
var common = require('common.js')

common.globalValue // 'c'