Modularization
You can extract some common code into a separate JavaScript file as a module. Modules can only expose interfaces to the outside world through export default
.
Note:
- Module directories are currently only supported in the
pages
directory of the application..
├── pages // Mini Program pages
│ ├── index // Mini Program page
│ │ ├── index.css // Styles for the Mini Program page
│ │ ├── index.dlt // Template for the Mini Program page
│ │ ├── index.js // Logic for the Mini Program page
│ │ └── index.json // Configuration for the Mini Program page
│ └── util // Mini Program utility methods
│ ├── i18n.js // Internationalization for the Mini Program
│ ├── request.js // Encapsulation of Mini Program request methods
│ └── xxx.js // Other common methods for the Mini Program
├── app.css // Global styles for the Mini Program
├── app.js // Global JavaScript logic for the Mini Program
└── app.json // Global configuration for the Mini Program - Mini Programs currently do not support direct imports from
node_modules
. When developers need to use code fromnode_modules
, it is recommended to copy the relevant code to the Mini Program directory.
// util/index.js
function sayHello(name) {
console.log(`Hello ${name} !`);
}
function sayGoodbye(name) {
console.log(`Goodbye ${name} !`);
}
export default {
sayHello,
sayGoodbye,
};
// index/index.js
import test from "../util/index";
Page({
onShow() {
test.sayHello();
},
});