Recently RECEIVED a new project, do a micro channel small program. I did a little program a long, long time ago, but it was a long time ago, about the first year of the little program. In the last two days received a small program was search down the right of notice 😅, probably has been a long time not to maintain. So this time maybe maybe maybe we have to go back to the drawing board. Some of the stuff on the development document is not discussed here, and the specific business logic is not discussed here, so let’s make some nonsense. hhh

1. Set a proper directory structure

This should be the first question that comes to my mind. How can we make each module of the project more orderly? Project probably included pages, the components, the resource, utils, env, and is the need to use some of the script files in the root directory. The diagram below:

  • First, let’s talk about the organization mode of pages and Components, which are the most critical modules. First, according to specific business logic, different functional modules should be split, such as personal center, courses, blog, etc. Set a folder for each module. Like the picture below

The /pages/course folder contains all the pages for the course modules, as well as a /pages/ Course/Components folder (which only holds component files for the course modules). Some common components, of course, should be placed in the outermost /components folder.

  • /utilsIt mainly stores some tool files, such as constant files, request encapsulation files, parameter encryption method encapsulation files, common function files and so on. The following figure

  • /resourceAs the name implies, static resource files, such as images, fonts, audio, etc.
  • /envThe folder used to store environment variable files, which will be covered in more detail in section 4.

Summary: by now I have probably made my directory structure setup clear. By the way, I have some thoughts during this period.

  • Resource folder Settings. We considered setting a resource folder for each module directory, but later found this inconvenient when we actually wrote the code. For example, at the end I compressed all the resource files, imagine if they were scattered in different function directories, it would be really cracked. Fortunately, I realized the problem and corrected it in time. Of course,/resourceThe directory structure is also the same/pagesSimilar. Easy to find quickly.
  • Component directory Settings,Plan aSet a component folder under each module,Scheme 2Set the component folder only in the following directory. First of all, option 1 has the same problem as the previous resource folder, and considering that many components are common under the same functional module, option 1 is not appropriate. Option 2 only sets the component folder in the root directory, considering that many components are only used in a specific function module, so Option 2 is not appropriate. Finally, the medium granularity scheme was selected, and one was set under each function modulecomponentsFolder.

2. Encapsulation of login functions

The specific wechat login process will not be said, mainly about the encapsulation of the login module. There are two possible methods: One is to register a behavior and then introduce the behavior where the login is needed. Behavior only addresses the reuse of JS code and is introduced repeatedly in modules (or even parent-child components) that need to be logged in. Wechat authorization relies on the native Button component, so it is necessary to set a popover to place the button in each component that needs to log in. Of course, this can achieve the function, but it is not elegant. Method two: Register a public login page. In the case of all modules that need login, navigateTo this page without login, do user information authorization, login, store token, etc., then nagivateBack to the previous page, of course, the previous page interface request is best written in the onShow lifecycle hook. Summary: finally, of course, chose the plan 2 cough up, and there is no problem with the current use. It was easy to figure it out, but it did take a while to think about it.

3. How to use SCSS in wechat developer tools

It’s Easy to use in vscode. Install Easy Sass and set setting.json. Then save it to generate a.wxss file in the same directory. But can it be so sweet in wechat developer tools, so I looked at the document, developer tools already support extension tools. The steps are as follows: 1. Install Easy Scss with VScode

2. Find the extension folder and unpack the folder~/.vscode/extensions(macOS) orC:\Users\ username \.vscode\extensionsIn Windows

3. Copy the extension folder to the Developer Tools Extension folder (Settings – Extension Settings – Edit custom extension – Open the extension folder), as shown in the following figure

4. Configuration setting. Json

Summary:At this point, you should be able to use SCSS happily in wechat developer tools. One more minor issue here is that it is not easy to find the specific file location on the MAC, so I first cp the vscode extension to the desktop and then drag it into the developer tools extension folder. Sounds like a reverse proxy for HHH.

4. How to set environment variables tips

So far, wechat mini program has not provided API or specific configuration methods to set environment variables for us, so we still have to figure out their own way. The general idea is to set up a configuration file (/utils/ basedata.js), import it where needed, and then use Node to process the configuration file in different situations. The specific steps are as follows:

  • Set up a basedata.js file

  • Introduce it where it is needed

This completes the first step, introducing the configuration file into the project

  • Create a new directory in the root directory/envfolder

in/envCreate a folderdev.jsonandprod.jsonTwo JSON files, one for development environment and one for production environment constants.

  • Two new commands have been added under script of package.json to launch different environments

According to the command line parameters, select/envThe corresponding configuration file under

  • Create a new directory in the root directoryswitch.jsFile, using Node to process configuration information.
* Modify the project configuration information in /config.js according to the command line parameters. */ const fs = require('fs') const path = require('path') const sourceFiles = {prefix: '/env/', dev: 'dev. Json ', prod: 'prod.json'} // target file const targetFiles = [{prefix: '/utils/', filename: 'basedata.js'}] const preText = 'module.exports =' // Get command line arguments const cliArgs = process.argv.splice(2) const env = CliArgs [0] const isProd = env.indexof ('prod') > -1? Const sourceFile = isProd? Const sourceFile = isProd? sourceFiles.prod : Fs. readFile(__dirName + sourceFiles. Prefix + sourceFile, (err, data) => { if (err) { throw new Error(`Error occurs when reading file ${sourceFile}.nError detail: ${err} ') process.exit(1)} const targetConfig = json.parse (data) // Writes the retrieved content to the target file targetFiles.forEach(function(item, index) { let result = null if (item.filename === 'baseData.js') { result = preText + JSON.stringify(targetConfig, null, } console.log(result) fs.writefile (__dirname + item.prefix + item.filename, result, 'utf8', (err) => { if (err) { throw new Error(`error occurs when reading file ${sourceFile}. Error detail: ${err}`) process.exit(1) } }) }) })Copy the code

When we execute different commands, switch.js dynamically writes the corresponding environment configuration to the configuration file (/utils/ basedata.js). So this is pretty much where we want to be. But it’s not very convenient to run the NPM script every time you switch environments.

  • So the last key step is to configure our developer tool to automatically execute the corresponding NPM script before previewing, uploading, etc.

In the developer Tools local Settings, you can select enable custom processing commands, as shown in the following figure

Summary:After that, you basically implement different environments with different variables. Update the corresponding environment each timejsonDocuments, so to speak, are very convenient.

5. Choose the right UI framework

This will not be specific to expand, refer to the article many 👀 summary of 9 excellent open source small program UI framework I finally choose Vant. Because I am familiar with Vant, but this vant is not the same vant, compared to the Web version, it is a beggar’s shop. Well, if YOU give me another chance, I think…

7. Other details

7.1 Page Initialization Request onLoad or onShow

The original is based on reducing the number of requests, reduce the pressure on the server. I’m going to put all the requests in onLoad. However, it was found during the development that some interface data depend on login status and other states, such as VIP status, which is more appropriate to put in onShow (mainly considering that these states will change from time to time).

7.2 You do not need setData to modify data

Here’s an excerpt from the best practices section of the development document:

The setData operation causes the framework to handle some of the work associated with rendering the interface. An unbound variable means that it has nothing to do with rendering the interface, and passing in setData incurs unnecessary performance costs.

All data passed in by setData has dependencies in the template rendering

So sometimes you don’t need to use setData to modify data 🦆, such as page, directly this.data.page++ can be used.

7.3 Network Request Encapsulation

Wechat provides an API for initiating network requests — wx.request(), and provides various callback functions. It’s easy to just use it and go back to hell. So there are probably three reasons for encapsulation:

  • Promise to change
  • Set a unified request header
  • Obtain uniform interface callback handling capabilities

The specific code is as follows:

Import baseData from './baseData' // Request package const baseUrl = baseData. ApiBaseUrl const Timeout = 20000 //// Request timeout time const header = { 'content-type': 'application/x-www-form-urlencoded' } function fetch(options) { if (options.loading) { wx.showLoading({ title: } return new Promise(function(resolve, reject) {wx.request({url: `${baseUrl}${options.url}`, method: options.method || 'GET', data: getParams(options.data), header: header, timeout: timeout, Success (res) {if(res.data.return_code === '2003') {/// /token invalid wx.removeStoragesync ('accessToken')} resolve(res)}, fail (err) { reject(err) }, complete () { if (options.loading) { wx.hideLoading() } } }) }) } export function post(url, params, loading=false) { let options = { method: 'POST', url: url, data: params, } return fetch(options) }Copy the code

Conclusion: Finally used two days of fragmentary time to gibberish over. Combined with the development documentation, you should be able to develop smoothly. I will not squeeze the water, the eldest brothers pick their own look.

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign