Using Webpack to Realize Multi-project Management of Small Programs

Keywords: Front-end Webpack JSON npm git

This is how the story begins.

Front-end development brother Bingo receives the demand of product ladies and sisters, and has to go online with several small programs.

Code Animal Brother Begins Architecture

  • Miscellaneous small procedures, put a project to facilitate management
  • There are many small programs, so the code should be reusable.
  • Team development, code style should be unified

Code Animal Brother Started Construction Project

This is the basic directory structure for a single applet, no problem.

When a project has many small programs, it seems that it's okay.

When multiple widgets use the same component com3, Brother finds that the code can not be reused and needs to be copied and pasted.

Think about it, then move the component directory outside so that it can not be reused?

It feels good. Brother opens demo1 in the Wechat Developer Tool and finds out that he has made a mistake.

The original widget is the current project as the root directory, the components directory is no longer within the scope of the demo1 directory, so it can not be referenced.

The little brother thought of Webpack

1. Cataloguing

  • apps/: Store all the applets
  • Build /: Stores build scripts
  • common/: Storing public methods
  • Components/: Store common components
  • Styles/: Store common styles
  • Templates/: Store common templates

It's about this long.

2. Write build scripts

package.json

script: {
  "dev": "webpack --config build/webpack.config.js"
}

build/webpack.config.js

The idea is to use Copy Web pack Plugin to synchronize the specified files into the widget directory

const CopyWebpackPlugin = require('copy-webpack-plugin')
const utils = require('./utils')

// Get the applet in the apps directory and specify the name of the common file directory
function copyToApps(dir) {
  let r = []

  utils
    .exec(`cd ${utils.resolve('apps')} && ls`)
    .split('\n')
    .map(app => {
      r.push({
        from: utils.resolve(dir),
        to: utils.resolve(`apps/${app}/_${dir}`)
      })
    })

  return r
}

module.exports = {
  watch: true,

  // Listen for entrance files, save them and refresh them
  entry: utils.resolve('index.js'),

  output: {
    path: utils.resolve('.tmp'),
    filename: 'bundle.js'
  },

  plugins: [
    // Synchronize specified public files to all applet directories
    new CopyWebpackPlugin([
      ...copyToApps('styles'),
      ...copyToApps('common'),
      ...copyToApps('templates'),
      ...copyToApps('components')
    ])
  ]
}

3. Start local development

npm run dev

Now the common code has been automatically synchronized to the widget directory, starting with the underline, when changing the common code will automatically synchronize to the widget call.

The invocation is long like this

import utils from './_common/utils'
import com3 from './_components/com3'
@import './_styles/index.wxss';
<import src="./_templates/index.wxml" />

Code style checking

package.json

script: {
  "lint": "eslint apps/"
}

.eslintrc.js

module.exports = {
  extends: 'standard',

  // Exclude global variables specific to small programs
  globals: {
    Page: true,
    Component: true,
    App: true,
    getApp: true,
    wx: true
  },

  rules: {
    'space-before-function-paren': ['error', 'never'],
    'no-unused-vars': [
      'error',
      {
        // The applet does not yet support ES7, which is compatible with async/await.
        varsIgnorePattern: 'regeneratorRuntime'
      }
    ]
  }
}

Then with the help of husky Perform validation before each git commit

script: {
  "precommit": "npm run lint"
},

devDependencies: {
  "husky": "^0.14.3"
}

Clear

Finally, the younger brother added a clean-up command to facilitate the re-generation of public code.

package.json

script: {
  "clean": "node build/clean.js"
}

build/clean.js

const rimraf = require('rimraf')
const utils = require('./utils')

function log(dir) {
  console.log(`cleaning ${dir}`)
}

rimraf(utils.resolve('.tmp'), () => log('.tmp'))

utils
  .exec(`cd ${utils.resolve('apps')} && ls`)
  .split('\n')
  .map(app => {
    ;[
      `${app}/_styles`,
      `${app}/_common`,
      `${app}/_templates`,
      `${app}/_components`
    ].map(m => {
      rimraf(utils.resolve(`apps/${m}`), () => log(m))
    })
  })

The little brother of the yard animal is satisfied.

"It's time to catch up with the drama after work."

Brief Introduction of the Code Animal Brother

Koala front-end development brother Bingo, research small program development.

Posted by maniac1aw on Fri, 10 May 2019 10:38:01 -0700