Skip to content

Modularity

require

Introduce module. Return module through module.exports or the interface exposed by exports.

When you need to import modules from other subpackages, you can configure the callback callback function to asynchronously obtain the specified module. When the asynchronous acquisition fails, the error callback function will be triggered.

Parameter

NameTypeIs it required?Required
pathstringYesThe relative path of the module file relative to the current file, or the npm module name, or the npm module path needs to be imported. Absolute paths are not supported by default, and you can customize the path mapping by configuring resolveAlias
callbackfunctionNoAsynchronous loading success callback function, the callback function parameter is the successfully loaded module
errorfunctionNoAsynchronous loading failure callback function, the callback function parameter is the error message and module name

require.async chain call

Can be used by chain call

js
require
    .async('path/to/mod')
    .then((mod) => {
        console.log(mod)
    })
    .catch(({ errMsg, mod }) => {
        console.error(`path: ${mod}, ${errMsg}`)
    })

Sample code:

Call in the same package

js
// common.js
function sayHello(name) {
  console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
  console.log(`Goodbye ${name} !`)
}


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

Cross-package asynchronous calls

js
// subpackage/common.js Subcontracting common files
export const sayHello = () => console.log("hello")
js
// pages/index.js main package page
let common;
require('../../subpackage/common.js', (mod) => {
    common = mod
}, ({ errMsg, mod }) => {
    console.error(`path: ${mod}, ${errMsg}`)
})

Page({
    sayHello() {
        common && common.sayHello()
    }
})

module

Object module

Current module object

Properties

PropertiesTypeDescription
exportsObjectThe object exposed by the module, when using require to reference the module, you can get the reference to

Sample code:

js
// common.js
function sayHello(name) {
  console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
  console.log(`Goodbye ${name} !`)
}


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

exports

Object exports

module.exports.

Sample code:

js
// common.js
function sayHello(name) {
  console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
  console.log(`Goodbye ${name} !`)
}


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