


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

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

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

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. ...

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.

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.

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.

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...

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...

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.

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.
