Home  >  Article  >  WeChat Applet  >  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

Y2J
Y2JOriginal
2017-05-04 10:23:482315browse

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!

Statement:
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