preface

I’m used to using Webpack for engineering project development, but I feel a little uncomfortable after contacting small programs. There are excellent small program frameworks such as Taro on the market that can be used. Due to the historical background of the project, it is impossible to make large-scale transformation, so I can only do some simple engineering programs

Standard code

  • Configuration eslint
  • Vscode installs the plugin esLint
  • Configure husky to use git commit hooks for ESLint checks that fail to commit code

1.package.json

"lint-staged": {
    "**/*.(js)": [
      "pretty-quick --staged"."eslint --ext .js"."git add"]."run/*": [
      "git rm --cached"]},"husky": {
    "hooks": {
      "pre-commit": "npm run build && git add . && lint-staged"}}Copy the code

2. Configuration. Eslintrc

module.exports = {
  root: true.parser: 'babel-eslint'.parserOptions: {
    sourceType: 'module',},env: {
    browser: true.node: true.es6: true,},extends: 'eslint:recommended'.plugins: ['import'].rules: {
    'arrow-body-style': [2.'as-needed'].'wrap-iife': [2.'inside'].camelcase: [
      0,
      {
        properties: 'always'.ignoreDestructuring: true],},'no-var': 2.'one-var': [2.'never'].'no-undef-init': 2.'default-case': 2.'prefer-template': 0.'no-useless-concat': 2.'no-multi-str': 2.'no-new-object': 2.'object-shorthand': [2.'always'].'prefer-object-spread': 2.'no-array-constructor': 2.'max-params': [2.6].'prefer-rest-params': 2.'no-useless-constructor': 2.'no-eval': 2.'no-throw-literal': 2.'import/no-unresolved': [2, { commonjs: true.amd: true}].'import/namespace': 2.'import/default': 2.'import/export': 2.'no-unused-vars': [
      'error',
      {
        vars: 'all'.args: 'after-used'.ignoreRestSiblings: false,}]},globals: {
    wx: true.App: true.Page: true,}};Copy the code

3. Configure the project file.vscode/settings.json, which is automatically checked by ESLint when saved

{
  "files.associations": {
    "*.wxml": "xml",},"eslint.enable": true."eslint.options": {
    "extensions": [".js"]},"eslint.validate": ["javascript"]."eslint.run": "onSave"
}
Copy the code

Formatting code -prettier

1. Install Prettier, pretty-quick and configure. Prettierrc

{
  "printWidth": 120."singleQuote": true."tabWidth": 2."useTabs": false."trailingComma": "es5"."insertPragma": false."endOfLine": "lf"."semi": true."trailingCommas": "es5"."arrowParens": "avoid"."overrides": [{"files": "*.wxml"."options": {
        "parser": "html"}}}]Copy the code

2. Configure the.vscode/settings.json project to be automatically formatted when saving

{
  "editor.formatOnSave": true
}
Copy the code

Unit tests – Jest

1. Install jest, @babel/core, @babel/preset-env, and babel-jest

2. The configuration package. Json

"scripts": {
    "test": "jest ./test/index.test.js --coverage"
}
Copy the code

3. Edit. Babelrc

{
  "presets": ["@babel/preset-env"]}Copy the code

4. Create the test test folder

  • Create index. Test. Js
require('./unit/xxx.test.js');
Copy the code

5. Write test scripts

import { sum } from '.. /util.js'; () => {test('adds 1 + 2 to equal 3', () => {expect(sum(1, 2)).tobe (3); }); });Copy the code

Injecting environment variables

Scheme 1: rollup

1. Install rollup and @rollup/plugin-replace

2. The configuration package. Json

"scripts": {
    "dev": "rollup -c --environment NODE_ENV:dev"."build": "rollup -c --environment NODE_ENV:prod",}Copy the code

3. At git commit time, the system automatically switches back to the build environment

"lint-staged": {
    "**/*.(js)": [
      "pretty-quick --staged",
      "eslint --ext .js",
      "git add"
    ],
    "run/*": [
      "git rm --cached"
    ]
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run build && git add . && lint-staged"
    }
  }
Copy the code

4. Create the environment base file env_base.js (do not move)

// Environment variables, do not move
export default CUR_ENV;
Copy the code

5. Rollup.config. js configuration file

import replace from '@rollup/plugin-replace';
export default {
  input: 'env_base.js'.output: {
    file: 'env.js',},plugins: [
    replace({
      include: 'env_base.js'.exclude: 'node_modules/**'.CUR_ENV: JSON.stringify(process.env.NODE_ENV), // Inject environment variables})]};Copy the code

6. NPM run dev/build generates env.js

7. The business code is introduced into env.js to get the injected environment variables to distinguish the environment

Scheme 2: Node

  • Solution 1: Create an additional base file env_base.js and integrate rollup, which is not good for lightweight applications!
  • Scheme 2: Using the basic capabilities of Node, directly generate the current environment variable file env.js, remove the rollup framework, and reduce the cost of technology migration

1. Environment switchover command

"scripts": {
    "dev": "NODE_ENV=dev node ./set-env.js"."build": "NODE_ENV=prod node ./set-env.js"
},
Copy the code

2. At git commit time, the system automatically switches back to the build environment

"lint-staged": {
    "**/*.(js)": [
      "pretty-quick --staged"."eslint --ext .js"."git add"]."run/*": [
      "git rm --cached"]},"husky": {
    "hooks": {
      "pre-commit": "npm run build && git add . && lint-staged"}}Copy the code

3. Switch script (set-env.js)

// Switch the environment
const { createWriteStream } = require('fs');
const { resolve } = require('path');
// The current environment variable
const CUR_ENV = process.env.NODE_ENV || 'prod';
// What to write
const content = `const CUR_ENV = '${CUR_ENV}';
export default CUR_ENV;
`;
/ / create the stream
const fileName = resolve(__dirname, './env.js');
const ws = createWriteStream(fileName, {
  encoding: 'utf8'.autoClose: true}); ws.on('open'.function () {
  console.log('Setting environment variable.... `);
});
ws.on('finish'.function () {
  console.log('Setting environment variable succeeded:${CUR_ENV || 'Online Environment'}`);
  process.exit();
});
ws.on('error'.function () {
  process.exit(1);
});
ws.write(content);
ws.end();
Copy the code

4. NPM run dev/build, generate env.js file, and export environment variables

const CUR_ENV = 'dev'; // 'prod', export default CUR_ENV;Copy the code

5. Business code is introduced into env.js to obtain the injected environment variables to distinguish the environment