# require
Introduce the module.Return module through module.exports Orexportsexposed interfaces.
When another subcontracted module needs to be introduced, the specified module can be retrieved asynchronously by configuring thecallbackcallback function.When asynchronous fetch fails, theerrorcallback is triggered.
# parameter
| name | type | Required to fill in | Introductions |
|---|---|---|---|
| path | string | yes | You need to introduce the relative path of the module file relative to the current file, or the npm module name, or the npm module path.Absolute paths are not supported by default, and custom path maps can be defined by configuringresolveAlias. |
| callback | function | no | Asynchronously load a successful callback function, which parameters are the successfully loaded module. |
| error | function | no | An asynchronous load failure callback function, which parameters are error message and module name. |
# Require.async Chain Call
It can be used by chain call.
require
.async('path/to/mod')
.then((mod) => {
console.log(mod)
})
.catch(({ errMsg, mod }) => {
console.error(`path: ${mod}, ${errMsg}`)
})
# sample code
# Call within the same package
// common.js
function sayHello(name) {
console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
console.log(`Goodbye ${name} !`)
}
module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye
var common = require('common.js')
Page({
helloMINA: function() {
common.sayHello('MINA')
},
goodbyeMINA: function() {
common.sayGoodbye('MINA')
}
})
# Asynchronous calls across subpackages
// Subpackage / common.js subpackage common file
export const sayHello = () => console.log("hello")
// 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()
}
})