02. 小程序目录结构
微信小程序有一套完整的目录结构规范,了解它有助于组织项目代码。
标准目录结构
project-name/
├── pages/ # 页面目录
│ ├── index/ # index 页面
│ │ ├── index.js # 页面逻辑
│ │ ├── index.json # 页面配置
│ │ ├── index.wxml # 页面结构
│ │ └── index.wxss # 页面样式
│ └── profile/ # profile 页面
├── utils/ # 工具函数
├── components/ # 组件目录
├── images/ # 图片资源
├── app.js # 小程序逻辑
├── app.json # 小程序配置
├── app.wxss # 小程序全局样式
└── project.config.json # 项目配置核心文件介绍
1. app.js
小程序入口文件,初始化配置和全局数据。
javascript
App({
onLaunch() {
// 小程序启动时触发
console.log("小程序启动");
},
onShow() {
// 小程序从后台进入前台显示时触发
},
onHide() {
// 小程序从前台进入后台时触发
},
globalData: {
userInfo: null,
// 全局数据
}
});2. app.json
小程序全局配置文件。
json
{
"pages": [
"pages/index/index",
"pages/profile/profile"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "我的小程序",
"navigationBarTextStyle": "black"
},
"tabBar": {
"list": [
{
"pagePath": "pages/index/index",
"text": "首页",
"iconPath": "images/icon-home.png",
"selectedIconPath": "images/icon-home-active.png"
},
{
"pagePath": "pages/profile/profile",
"text": "我的",
"iconPath": "images/icon-profile.png",
"selectedIconPath": "images/icon-profile-active.png"
}
]
},
"style": "v2",
"sitemapLocation": "sitemap.json"
}3. 页面文件
每个页面包含四个文件:
javascript
// index.js
Page({
data: {
msg: "Hello, 小程序!"
},
onLoad(options) {
// 页面加载时触发
},
onShow() {
// 页面显示时触发
},
onReady() {
// 页面初次渲染完成时触发
},
onHide() {
// 页面隐藏时触发
},
onUnload() {
// 页面卸载时触发
},
handleTap() {
// 事件处理函数
}
});json
// index.json
{
"navigationBarTitleText": "首页"
}xml
<!-- index.wxml -->
<view class="container">
<text>{{msg}}</text>
<button bindtap="handleTap">点击</button>
</view>css
/* index.wxss */
.container {
padding: 20rpx;
}总结
了解小程序目录结构是开发的基础,按照规范组织代码可以提高开发效率。