Table of Contents
Before you start, you need to prepare
Download WeChat applet developer tools
Use the npm command to start a WeChat applet project
Start installing the necessary dependent modules
Directory structure" >Build the projectDirectory structure
Write the build script
Define npm command
Home WeChat Applet Mini Program Development Teach you detailed steps to improve the efficiency of WeChat mini program development

Teach you detailed steps to improve the efficiency of WeChat mini program development

May 04, 2017 am 10:23 AM

The API implementation of the WeChat applet needs to take into account all aspects, so the callback writing method is still used.

As we all know, Callback-Hell is a historical problem in traditional JS syntax. But after all, handy tools are the source of development efficiency, so the author has made a simple encapsulation of the current version of the WeChat applet API - weapp.

At the same time, the WeChat applet framework itself focuses on the implementation of interaction and UI, and does not provide built-in status management. If many asynchronous operations are implemented directly in App or Page, I believe it will be difficult to develop and difficult to test.

Therefore, I implemented a state management module based on the Redux solution for the WeChat applet to facilitate application state management redux-weapp in the applet.

Specially, WeChat applet does not support requiring files from outside the App scope when building (compiling), so npm is not easy to use here.

So, we need to build dependencies locally in the application in real time and reference local modules in the WeChat applet.

For this kind of construction scenario, I think webpack is the most convenient solution.

Before you start, you need to prepare

  • Understand what the WeChat applet is from the official documentation;

  • Understand Redux Application state management solution, it is also the specific implementation of Flux architecture;

  • UnderstandJavaScript packaging tool webpack;

  • Learn about the ES6/7 code translation (transcompile) tool Babel. The principle is to use syntax analysis tools to parse the code into an abstract syntax tree and then "rewrite" it into the final code;

  • Similar to Jest, Mocha and other JavaScript testing tools, you can choose according to your needs.

InstallationTools and dependent modules

Download WeChat applet developer tools

The developer tools use NW.js The simulated environment, in WeChat, is the JavascriptCore environment.

But don’t worry, they are just two different VMs, but the essence is the same.

NW.js may have some minor bugs, just pay attention to it when writing code.

Use the npm command to start a WeChat applet project

mkdir myappcd myapp
npm init
Copy after login

Start installing the necessary dependent modules

Since in addition to the modules required for running the applet, there are also the modules required for construction module.

It seems like there will be more, but don’t worry, most of them are declarative and don’t require you to call them directly.

In order to facilitate the understanding of students with less experience, I will install these dependencies step by step.

The first is the code translation tool Babel:

npm install --save-dev babel-cli babel-core babel-loader babel-plugin-add-module-exports babel-polyfill babel-preset-es2015 babel-preset-stage-0
Copy after login

With the above modules, you can translate ES6/7 code into ES5 code during build (in fact, the interpreter only Recognize ES5).

Next, we install the packaging tool webpack:

npm install webpack --save-dev
Copy after login

We only need to package the code, without the dev server and hot module replace functions.

Therefore, we only need to install the webpack module itself, without installing other extensions and plug-ins.

Next, let’s install Redux:

npm install redux redux-thunk --save-dev
Copy after login

It should be noted that in actual applications, we often need to asynchronously call the interface of the API server, so We also need the redux-thunk module to handle asynchronous behavior.

Then install the auxiliary module for developing mini programs:

npm install xixilive/weapp xixilive/redux-weapp --save-dev
Copy after login

Among them, the weapp module is a wrapper for the WeChat mini program API, providing an easier-to-use API, and redux-weapp is based on Redux. WeChat applet for status management.

Build the projectDirectory structure

myapp
 |- es6                # 源代码
   |- myapp.js         # 在app.js文件中require此文件
 |- lib                # 存放编译之后的js文件
 |- pages              # 小程序页面定义
   |- projects
     |- projects.js
     |- projects.json
     |- projects.wxml
     |- projects.wxss
   ...
 |- app.js             # 小程序入口文件
 |- app.json
 |- app.wxss
 |- webpack.config.js  # webpack配置文件
Copy after login

Write the build script

First you must write webpack.config.js, this is required of.

Since this build is to localize the dependencies of the WeChat applet, we only process JS files. If you need to package other resources, please do your own research.

Also, it is worth noting that the WeChat mini program package has an upper limit of 1 MB.

// webpack.config.jsvar path = require('path'), webpack = require('webpack')var jsLoader = {
  test: /\.js$/, // 你也可以用.es6做文件扩展名, 然后在这里定义相应的pattern
  loader: 'babel',
  query: {    // 代码转译预设, 并不包含ES新特性的polyfill, polyfill需要在具体代码中显示require
    presets: ["es2015", "stage-0"]
  },  // 指定转译es6目录下的代码
  include: path.join(dirname, 'es6'),  // 指定不转译node_modules下的代码
  exclude: path.join(dirname, 'node_modules')
}module.exports = {  // sourcemap 选项, 建议开发时包含sourcemap, production版本时去掉(节能减排)
  devtool: null,  // 指定es6目录为context目录, 这样在下面的entry, output部分就可以少些几个`../`了
  context: path.join(dirname, 'es6'),  // 定义要打包的文件  // 比如: `{entry: {out: ['./x', './y','./z']}}` 的意思是: 将x,y,z等这些文件打包成一个文件,取名为: out  // 具体请参看webpack文档
  entry: {
    myapp: './myapp'
  },

  output: {    // 将打包后的文件输出到lib目录
    path: path.join(dirname, 'lib'),    // 将打包后的文件命名为 myapp, `[name]`可以理解为模板变量
    filename: '[name].js',    // module规范为 `umd`, 兼容commonjs和amd, 具体请参看webpack文档
    libraryTarget: 'umd'
  },  module: {
    loaders: [jsLoader]
  },

  resolve: {
    extensions: ['', '.js'],    // 将es6目录指定为加载目录, 这样在require/import时就会自动在这个目录下resolve文件(可以省去不少../)
    modulesDirectories: ['es6', 'node_modules']
  },

  plugins: [    new webpack.NoErrorsPlugin(),    // 通常会需要区分dev和production, 建议定义这个变量    // 编译后会在global中定义`process.env`这个Object    new webpack.DefinePlugin({      'process.env': {        'NODE_ENV': JSON.stringify('development')
      }
    })
  ]
}
Copy after login

Define npm command

The first is the code test command test.

Since I like to use Jest, I also use Jest as an example here.

// package.json"scripts": {  "pretest": "eslint es6", //推荐进行静态检查  "test": "jest",
  ...
},
...,// jest允许在package.json中定义配置"jest": {  "automock": false,  "bail": true,  "transform": {    ".js": "/node_modules/babel-jest" //用babel转译
  },  "testPathDirs": [    "/tests/"
  ],  "testRegex": ".test.js$",  "unmockedModulePathPatterns": [    "/node_modules/"
  ],  "testPathIgnorePatterns": [    "/node_modules/"
  ]
}
Copy after login

Next, is the exciting build command. Success or failure lies in one fell swoop

The above is the detailed content of Teach you detailed steps to improve the efficiency of WeChat mini program development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

What is the difference between H5 page production and WeChat applets What is the difference between H5 page production and WeChat applets Apr 05, 2025 pm 11:51 PM

H5 is more flexible and customizable, but requires skilled technology; mini programs are quick to get started and easy to maintain, but are limited by the WeChat framework.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? Apr 01, 2025 pm 10:48 PM

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...

How to solve the problem of JS resource caching in enterprise WeChat? How to solve the problem of JS resource caching in enterprise WeChat? Apr 04, 2025 pm 05:06 PM

Discussion on the JS resource caching issue of Enterprise WeChat. When upgrading project functions, some users often encounter situations where they fail to successfully upgrade, especially in the enterprise...

How to choose H5 and applets How to choose H5 and applets Apr 06, 2025 am 10:51 AM

The choice of H5 and applet depends on the requirements. For applications with cross-platform, rapid development and high scalability, choose H5; for applications with native experience, rich functions and platform dependencies, choose applets.

What are the development tools for H5 and mini program? What are the development tools for H5 and mini program? Apr 06, 2025 am 09:54 AM

H5 development tools recommendations: VSCode, WebStorm, Atom, Brackets, Sublime Text; Mini Program Development Tools: WeChat Developer Tools, Alipay Mini Program Developer Tools, Baidu Smart Mini Program IDE, Toutiao Mini Program Developer Tools, Taro.

See all articles