preface

For vUE multi-page configuration, can say cli2-CLI3, is a process from 0 to 1, think of the UNBEARABLE cli2, CLI3 is fragrant is not a bit; Although CLI3 itself provides the entrance configuration of pages pages, but want to flexibly adapt to the structure according to the configuration, still need some operations, avoid the late non-stop modification; This article will cooperate with Node to do a flexible configuration and set up some just needed configuration plus performance optimization.

Create a project

  • Mode of operation

    vue create xxx ... . Select configuration (non-routing mode)... . Has been createdCopy the code
  • The project structure

Analysis of vue. Config. Js

  • The original code

    module.exports = {
    lintOnSave: false
    }
    Copy the code
  • Official website multi-page configuration code

    Module. exports = {pages: {index: {// page entry: 'SRC /index/main.js', // template source template: 'public/index.html', // in dist/index.html output filename: 'index.html, / / when using title option, / / title of the template tag needs to be < title > < % = htmlWebpackPlugin. Options. The title % > < / title > title: 'Index Page', // Blocks contained in this Page will by default contain generic chunks and Vendor chunks extracted by //. chunks: ['chunk-vendors', 'chunk-common', 'index']}, // If entry only string formats are used, // templates are inferred to 'public/subpage.html' // and if not found, Go back to 'public/index.html'. // The output file name is derived to 'subpage.html'. subpage: 'src/subpage/main.js' } }Copy the code

Analysis before modification

  • First of all, we draw a conclusion from the code provided on the official website, that is, multi-page is actually a list of unified entry. Therefore, when there is a need for new pages, in order not to manually modify the data information of the list, we need to script this section.
  • Secondly from the first point of view, multi-page structure and initialization of the structure is inconsistent, so we first step to modify the entire template rendering structure, do add and delete processing, of course, delete is not just needed, but the redundant structure will be meaningless;

Modify – Adjust the structure

SRC add template entry folder, name arbitrary, originally use pages as entry folder, structure is as followsCopy the code

Modify – Write multi-page configuration logic

The above structure has been built, let’s adjust the logic, first of all, let’s set the steps;

Step one, how flexible? Solution: read configuration from list with script; Part two, how do I read it? Solution: Use node fs to read folder information as entry configuration informationCopy the code

The plan has, we adjust directly below;

// -----------------------------pages config---------------------------------- const fs = require('fs') let pages = {} const _configPages = async function () { await fs.readdirSync('./src/pages/').forEach((val) => { pages[val] = { // page SRC /pages/${val}/index.js', // 'SRC /pages/${val}/index.html', // in dist/index.html output filename: `${val}.html` } }) } _configPages('./src/pages/') // readdirSync module.exports = { pages: pages // more pages config }Copy the code

Note: The only key is the name of each template folder. There is no need to change the name of the file in the template folder, so every time you add a page, just run again

Gzip optimization for performance optimization

First of all, gzip, in the most intuitive sense, will occupy the bandwidth resources of the server, but relative to the loss of large files, it is very worthwhile, and currently the mainstream cloud CDN, default enabled Gzip, so gzip in advance, is often the best way to improve performance. Go to a configureWebpack, Compression - webpackplugin const CompressionWebpackPlugin = require('compression-webpack-plugin') const gzipSourceList = ['css', 'js'] module.exports = { configureWebpack: config => { // open gzip if (process.env.NODE_ENV === 'production') { config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true return { plugins: [new CompressionWebpackPlugin({filename: '[path].gz[query]', // Algorithm: 'gzip', test: New RegExp (' \ \. (' + gzipSourceList. Join (' | ') + ') $'), / / match all the corresponding documents threshold: 10240, how many KB / / configuration 10 KB minRatio: 0.8, // compression ratio deleteOriginalAssets: false // whether to deleteOriginalAssets})]}}}}Copy the code

Other parameters need to be configured

Module. Exports = {publicPath: '/ [name] /, / / root directory | "/" suggests making outputDir: './dist/[name]/', // build path package output path productionSourceMap: false, // don·t use map do not exposed source devServer: {port: 1314, // port open: true, // default browser overlay: {// Display warnings: true, // eslint show warnings errors: true // eslint show errors } } }Copy the code

Structure development

In order to be highly flexible in development, some fetch and public file areas are reserved, structured as follows

  • The fetch – index entry

    import axios from 'axios'
      import qs from 'qs'
      
      function fetch (type, prefix, url, params, status) {
        return new Promise((resolve, reject) => {
          let postParams = {}
          const instance = axios.create({
            timeout: 100000
          })
          postParams = params
          let fetchData = {
            method: type,
            url: `${prefix}${url}`,
            data: qs.stringify(postParams)
          }
          if (type === 'get' || type === 'GET') {
          }
          instance(fetchData).then(response => {
            const res = response.data
            if (res.code === status) {
              resolve(res)
            } else {
              resolve(res)
            }
          }).catch(error => {
            reject(error)
          })
        })
      }
      
      export {
        fetch
      }
    Copy the code
  • fetch-api

    import { fetch } from './index' import { API_ROOT_CODE } from '.. /config/config' export default {getDemo (params) {// demo return fetch('get', API_ROOT_CODE, '/test/', params, 0) } }Copy the code

. . Etc. (omitted here, please refer to source code for other structure details)

A debugging tool

<script> var _hmt = _hmt || []; Function () {function () {function () {function () {function () {function () {function () { Const hostname = window.location.hostname if const domains = [ (domains. IndexOf (hostname) = = = 1) {var SRC = "/ / cdn.bootcss.com/eruda/1.2.4/eruda.min.js; document.write('<scr' + 'ipt src="' + src + '"></scr' + 'ipt>'); document.write('<scr' + 'ipt>eruda.init(); </scr' + 'ipt>'); }}) (); </script> ... .Copy the code

conclusion

This article is based on cli expansion optimization, basically applicable to the vast majority of the current project level multi-page development, welcome to put forward some valuable opinions and opinions, welcome to correct ~Copy the code

GIT source code, through train