The environment

  • The node v12.5.0
  • The system of win
  • Vuecli @ vue/cli 4.5.15
  • Ide WebStorm x64 2021.1

In this paper, the SPA application created by VUe-CLI is transformed into a multi-page application.

We can understand a multi-page application as an application composed of multiple single pages, and what is multiple single pages? In fact, you can think of a single page as an HTML file, and multiple single pages as multiple HTML files. A multi-page application is an application composed of multiple HTML files, as shown below:

  • The article sample code repository recommends a quick look at the article – look at the sample code.

Began to transform

Change directories

  • Each page of a multi-page application can have files and functions in the SRC directory of a single-page application
  • insrcUnder the newpagesFolder, willPublic folder index. HTML, SRC folder app. vue, main.jsCopy it to the appropriate application folder, change the file name, and then delete it.
  • Create the file directory as shown in the figure below, folder name does not require but need the same entry JS, HTML file side configuration multi-page will be used.
  • Take the Index folder for example
    • index.jsThe equivalent ofmain.js
    • index.htmlEquivalent to the public folderindex.html
    • index.vueEquivalent to the SRC folderApp.vue
  • srcUnder theThe router, store,Whether to keep the folder depends on the specific scenario, whether the application uses one folder or needs to be separated. For example, the applicationThe router, store,The files are so different that they need to be separated or usedThe namespaceIf they are almost the same, they can share a file (data is not shared).

Change the vue. Config. Js

  • Take a look at the Vuecli documentation first

  • Entry files are specified by default in single-page applicationsmain.js, multi-page application entry files are includedPage1.js, page2.js, index.jsThe number depends on the number of directories under the Pages folder, dynamically generating pages objects is a good choice.

Dynamically get the Pages object

  • The installationyarn add globScan the folder and return the files we need
const path = require('path')
const glob = require('glob')

// Configure pages multiple pages to get HTML and JS in the current folder
function getEntry (globPath) {
  const entries = {}
  let basename
  let tmp
  let pathname
  glob.sync(globPath).forEach(function (entry) {
    basename = path.basename(entry, path.extname(entry))
    tmp = entry.split('/').splice(-3)
    pathname = basename // The correct path to output js and HTML
    entries[pathname] = {
      entry: 'src/' + tmp[0] + '/' + tmp[1] + '/' + tmp[1] + '.js'.template: 'src/' + tmp[0] + '/' + tmp[1] + '/' + tmp[2].title: tmp[2].filename: tmp[2].chunks: ['chunk-vendors'.'chunk-common', tmp[1]]}})return entries
}

const pages = getEntry('./src/pages/**? /*.html')
Copy the code
  • The object can be obtained in thevue.config.jsFor printing

  • invue.config.jsIn themodule.exports Object writes a multi-page configuration (that is, one more Pages configuration than a single page)

Configure dynamic import of JS CSS files

  • Configure dynamic importhtml-webpack-pluginPlugin, multiple pages will exist multiple configurations only configure one will throw errors as shown below.

  • Mistakes are also confusing

  • You can do that

  • HTML uses dynamically configured JS. The red box in the CSS diagram shows the template syntax

Complete configuration

const path = require('path')
const glob = require('glob')

// Configure pages multiple pages to get HTML and JS in the current folder
function getEntry (globPath) {
  const entries = {}
  let basename
  let tmp
  let pathname
  glob.sync(globPath).forEach(function (entry) {
    basename = path.basename(entry, path.extname(entry))
    tmp = entry.split('/').splice(-3)
    pathname = basename // The correct path to output js and HTML
    entries[pathname] = {
      entry: 'src/' + tmp[0] + '/' + tmp[1] + '/' + tmp[1] + '.js'.template: 'src/' + tmp[0] + '/' + tmp[1] + '/' + tmp[2].title: tmp[2].filename: tmp[2].chunks: ['chunk-vendors'.'chunk-common', tmp[1]]}})return entries
}

const pages = getEntry('./src/pages/**? /*.html')

module.exports = {
  pages,
  publicPath: '/'.outputDir: 'dist'.assetsDir: 'assets'.filenameHashing: true.lintOnSave: true.productionSourceMap: false.devServer: {
    index: 'index.html'.// Start the serve page by default
    host: '0.0.0.0'.port: 8889.https: false.hotOnly: false.proxy: null
  },
  chainWebpack: config= > {
    Object.keys(pages).forEach(entryName= > {
      // Configure dynamic import of JS and CSS
      config
        .plugin(`html-${entryName}`)
        .tap(args= > {
          args[0].cdn = []
          return args
        })

      config.plugins.delete(`prefetch-${entryName}`)}}}Copy the code

Run-pack

Run the above configurationnpm run serveWill run all applications

+ index access ` ` ` + page1 visit http://localhost:8889/page1/#/ http://localhost:8889/#/ ` + page2 access `http://localhost:8889/page2/#/`Copy the code

The above configuration runsRun NPM run buildIt packages all the apps

  • When you access an application (using the Node library HTTP-server), it will access index.html by default, so you need to specify an HTML file for all applications except index
    • The index accesshttp://localhost:8889/#/
    • Page1 accesshttp://localhost:8889/page1.html/#/
    • Page2 accesshttp://localhost:8889/page2.html/#/
  • So you have to do some judgment work with pathsFor example, use character substitutionhtmlAnd other irrelevant characters.

Package a single application – take the Page1 folder as an example

  • Multiple pagespagesMultiple configurations can be used for a single applicationpagesThere is only one configuration.
  • This requires a place for configuration, which is done using an env file.

  • Root Directory Creation.env、.env.dev_page1、.env.pro_page1And write corresponding data.
    • .envAll environments are loaded to be used when all applications are packaged by default
    • .env.dev_page1Dev is loaded at local development time
    • .env.pro_page1Pro is packaged and loaded

  • To change thepackage.jsonscriptsconfiguration

  • Modify thevue.config.js The complete code can be found in the sample repository

To optimize the

  • The above dynamic configuration of js, CSS wrote two examples, can also configure data in the.env file, specified environment load specified file
  • Multiple entry JS files, introduced file configuration duplication, can extract a common JS, export a vue initialization function, store, router to do initialization.
  • Other compression packaging volume is not discussed in this article (everyone must have a skill!!)

Refer to the article

+ Introduction to Vue project construction and development