


Teach you detailed steps to improve the efficiency of WeChat mini program development
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
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
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
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
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
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配置文件
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') } }) ] }
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/" ] }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Thanks to netizens Qing Qiechensi, HH_KK, Satomi Ishihara and Wu Yanzu of South China for submitting clues! According to news on September 2, there are recent rumors that "iPhone 16 may not support WeChat." In response to this, a reporter from Shell Finance called Apple's official hotline. Apple's technical consultant in China responded that whether iOS systems or Apple devices can continue to use WeChat, and WeChat The issue of whether it can continue to be listed and downloaded on the Apple App Store requires communication and discussion between Apple and Tencent to determine the future situation. Software App Store and WeChat Problem Description Software App Store technical consultant pointed out that developers may need to pay fees to put software on the Apple Store. After reaching a certain number of downloads, Apple will need to pay corresponding fees for subsequent downloads. Apple is actively communicating with Tencent,

DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

Rumors of WeChat supporting iPhone 16 were debunked. Thanks to netizens Xi Chuang Jiu Shi and HH_KK for submitting clues! According to news on September 2, there are rumors today that WeChat may not support iPhone 16. Once the iPhone is upgraded to the iOS 18.2 system, it will not be able to use WeChat. According to "Daily Economic News", it was learned from people familiar with the matter that this rumor is a rumor. Apple's response: According to Shell Finance, Apple's technical consultant in China responded that the issue of whether WeChat can continue to be used on iOS systems or Apple devices, and whether WeChat can continue to be listed and downloaded in the Apple App Store, needs to be resolved between Apple and Tencent. Only through communication and discussion can we determine the future situation. Currently, Apple is actively communicating with Tencent to confirm whether Tencent will continue to

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

The OKX trading platform offers a variety of rates, including transaction fees, withdrawal fees and financing fees. For spot transactions, transaction fees vary according to transaction volume and VIP level, and adopt the "market maker model", that is, the market charges a lower handling fee for each transaction. In addition, OKX also offers a variety of futures contracts, including currency standard contracts, USDT contracts and delivery contracts, and the fee structure of each contract is also different.

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

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.
