Develop your first WeChat Mini Program from scratch

Introduction

Through this blog, you can familiarize yourself with starting from scratch, building a small program development environment, and running your first small program.

Mini Program Development Steps

1. Register an account
2. Download development tools to build a development environment
3. Create a project and write code
4. Check the effect on the mobile phone
Through the above four steps, you can create your own small program.

Register a WeChat Mini Program Account

After the registration is complete, it looks like this
insert image description here

Download development tools to build a development environment

Mini Program Development Tool Download Address

Just download the corresponding stable version, as shown below
insert image description here

After downloading and installing the tool, you need to scan the code to log in to open the tool. After logging in, the interface is as shown below
insert image description here

Create project and write code

Click + to create a new project
insert image description here
The APPID here needs to be viewed on the "Development Settings" interface
insert image description here

There are many templates to choose from, I chose a To do template
insert image description here

It will prompt an error message that there are no cloud development-related settings. Don’t worry about it for the time being. The program can still run, but there is no backend, data cannot be saved, and the backend cannot be interacted with. Here, choose real machine debugging, and then use your own WeChat to scan the QR code, and you will be able to see your first small program on your mobile phone.
insert image description here
insert image description here

View the effect on the mobile phone

The real machine running results are as follows:

Error message "The current applet is not configured with a cloud development environment, please configure your cloud development environment in envList.js" and click OK.

insert image description here

The front-end interface is still operable, and you can fill in the relevant attributes of the to-do items, but you cannot upload and save them.
insert image description here

Introduction to the role of files in the project

The project file of the WeChat Mini Program mainly consists of the following parts:

app.js: The entry file of the applet, which is used to register the applet instance and monitor the life cycle events of the applet.

App({
  async onLaunch() {
    this.initcloud()

    this.globalData = {
      // 用于存储待办记录的集合名称
      collection: 'todo',
      // 最大文件上传数量
      fileLimit: 2
    }
  },

  flag: false,
  /**
   * 初始化云开发环境(支持环境共享和正常两种模式)
   */
  async initcloud() {
    const shareinfo = wx.getExtConfigSync() // 检查 ext 配置文件
    const normalinfo = require('./envList.js').envList || [] // 读取 envlist 文件
    if (shareinfo.envid != null) { // 如果 ext 配置文件存在,环境共享模式
      this.c1 = new wx.cloud.Cloud({ // 声明 cloud 实例
        resourceAppid: shareinfo.appid,
        resourceEnv: shareinfo.envid,
      })
      // 装载云函数操作对象返回方法
      this.cloud = async function () {
        if (this.flag != true) { // 如果第一次使用返回方法,还没初始化
          await this.c1.init() // 初始化一下
          this.flag = true // 设置为已经初始化
        }
        return this.c1 // 返回 cloud 对象
      }
    } else { // 如果 ext 配置文件存在,正常云开发模式
      if (normalinfo.length != 0 && normalinfo[0].envId != null) { // 如果文件中 envlist 存在
        wx.cloud.init({ // 初始化云开发环境
          traceUser: true,
          env: normalinfo[0].envId
        })
        // 装载云函数操作对象返回方法
        this.cloud = () => {
          return wx.cloud // 直接返回 wx.cloud
        }
      } else { // 如果文件中 envlist 不存在,提示要配置环境
        this.cloud = () => {
          wx.showModal({
            content: '当前小程序没有配置云开发环境,请在 envList.js 中配置你的云开发环境', 
            showCancel: false
          })
          throw new Error('当前小程序没有配置云开发环境,请在 envList.js 中配置你的云开发环境')
        }
      }
    }
  },

  // 获取云数据库实例
  async database() {
    return (await this.cloud()).database()
  },

  // 上传文件操作封装
  async uploadFile(cloudPath, filePath) {
    return (await this.cloud()).uploadFile({
      cloudPath,
      filePath
    })
  },

  // 下载文件操作封装
  async downloadFile(fileID) {
    return (await this.cloud()).downloadFile({
      fileID
    })
  },

  // 获取用户唯一标识,兼容不同环境模式
  async getOpenId() {
    const {
      result: {
        openid,
        fromopenid
      }
    } = await (await this.cloud()).callFunction({
      name: 'getOpenId'
    }).catch(e => {
      let flag = e.toString()
      flag = flag.indexOf('FunctionName') == -1 ? flag : '请在cloudfunctions文件夹中getOpenId上右键,创建部署云端安装依赖,然后再次体验'
      wx.hideLoading()
      wx.showModal({
        content: flag, // 此提示可以在正式时改为 "网络服务异常,请确认网络重新尝试!"
        showCancel: false
      })
      throw new Error(flag)
    })
    if (openid !== "") return openid
    return fromopenid
  }
})

app.json: The global configuration file of the applet, which is used to configure global settings such as page path, window style, and network request.

{
  "pages": [
    "pages/list/index",
    "pages/add/index",
    "pages/file/index",
    "pages/edit/index",
    "pages/detail/index"
  ],
  "window": {
    "backgroundColor": "#F6F6F6",
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#F6F6F6",
    "navigationBarTitleText": "云开发待办",
    "navigationBarTextStyle": "black"
  },
  "sitemapLocation": "sitemap.json",
  "style": "v2"
}

app.wxss: The global style file of the applet, which defines the common style of all pages in the applet.

/* 引入 weui 组件 */
@import './miniprogram_npm/weui-miniprogram/weui-wxss/dist/style/weui.wxss';

page {
  --footer-height: 10vh;
  --button-size: 16vw;
  --button-color: #353535;
  --button-icon-size: 6vw;
}

page {
  background: #f6f6f6;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  min-height: 100vh;
  overflow-x: hidden;
}

button {
  background: initial;
}

button:focus {
  outline: 0;
}

button::after {
  border: none;
}

.form-group {
  width: calc(100% - 40px);
  margin: 10px 20px;
  border-radius: 10px;
  background: white;
}

.form-group_label {
  align-self: flex-start;
  margin-left: 20px;
  color: #8D8D8D;
  font-size: 15px;
}

.form-group_label:not(:first-child) {
  margin-top: 20px;
}

.form-cell {
  padding: 20px 15px;
}

.form-cell:not(:last-child) {
  border-bottom: rgba(0, 0, 0, 0.05) solid 1px;
}

.form-cell.inline {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

pages folder: This
folder contains all the pages of the applet, and each page usually consists of four files:
insert image description here

.js file: the logic file of the page, used to process the data and interaction logic of the page.
.wxml file: The structure file of the page, using HTML-like markup language to define the structure of the page.
.wxss file: the style file of the page, used to define the style of the page.
.json file: The configuration file of the page, which is used to configure some special settings of the current page, such as navigation bar title, pull-down refresh, etc.
utils folder: This folder is used to store utility files of applets, such as encapsulated network requests, utility functions, etc.

project.config.json: project configuration file, used to configure the project information, compilation configuration, etc. of the applet.

Other resource files: Other resource files that may be used in the development of applets, such as pictures, fonts, etc.

These files constitute the engineering structure of the WeChat Mini Program, and developers can modify and expand it as needed. During the development process, the main focus is on page files (including logic, structure, style, and configuration) and global configuration files. By writing and modifying these files, the functions and interface display of the applet are realized.

Summarize

The development of WeChat applets is relatively convenient. WeChat Mini Programs use front-end development technology, mainly based on HTML, CSS and JavaScript. If you are familiar with these technologies, it will be easier to develop Mini Programs.

Here are some conveniences of WeChat Mini Program development:

  1. Development tools: WeChat provides a complete set of development tools, including developer tools and debugging tools, which can facilitate code writing, debugging and previewing.

  2. Documentation and tutorials: WeChat officially provides detailed development documentation and tutorials, including development guides, API documentation, and sample codes, which can help developers quickly get started and solve problems.

  3. Front-end technology: WeChat mini-programs use front-end development technology, which may be more familiar and widely used than other platforms. Many front-end developers already have relevant skills and experience and can quickly start developing.

  4. Market and users: WeChat has a huge user base, and mini programs can be used directly in WeChat without downloading and installing, which is convenient for users to access and use.

  5. Openness: WeChat Mini Programs provide a wealth of openness, including access to WeChat users' personal information, payment, location, camera, etc., enabling more functions and interactive experiences.

Of course, the difficulty of specific development will still be affected by factors such as personal technical level and project complexity. But in general, the development of WeChat applets is relatively convenient and efficient, suitable for beginners and developers with certain front-end development experience.

Guess you like

Origin blog.csdn.net/yikezhuixun/article/details/132037831