SoFunction
Updated on 2025-03-09

Vue Multi-page Project Development Practical Guide

Single-page and multi-page applications

Single page application

SPA (single page application): a single page application, that is, a web project has only one page (i.e., an HTML file).

It is to divide all the contents of all pages of the entire project into many small pieces (that is, components), components that can be reused and can be adjusted at will, and each component is an independent part (including html, css and javascript code). Make another html (basically nothing), this html is a page container, and it is enough to directly introduce it when it needs to be placed. When jumping, just jump to the component. When a component needs to be loaded, js will dynamically create HTML and CSS in these components.

This type of project usually requires a router to redirect the page.

At the beginning, you only need to load related resources of js and css once. All content is included on the main page and is componentized for each functional module. A single page application jump means switching related components and refreshing only local resources.

Packaged page dist directory structure

dist
├── static
│   ├── css
│   ├── js
│   ├── img
│   ├── dll
│   └── ...
└── 
└── ...
└── ...

Multi-page application

MPA (multippage application): Multipage application, that is, a web project has multiple pages (that is, multiple HTML files).

It refers to an application with multiple independent pages (multiple html pages), and each page must be repeatedly loaded with related resources such as js and css. Multi-page application jumps, and the entire page resource needs to be refreshed.

The project is composed of multiple complete pages. Multiple page jumps to refresh all resources, and each public resource (js, css, etc.) needs to be reloaded selectively.

Packaged page dist directory structure

dist
├── page(Which folder to package the name here?)
│   ├── css
│   ├── js
│   ├── img
│   ├── 
│   └── 
│   └── 
│   └── ....html
│   └── ....html
.   ....
.   ....
.   ....

Pros and cons

Pros and cons of single page application

advantage
Have a good interactive experience. It can improve the page switching experience. Users will not frequently switch to browse pages when visiting the application page, thereby avoiding page reloading.
A single page requests all the code (HTML, JavaScript and CSS) of the web application at once. Sometimes, considering that the first screen is loading too slowly, it will load on demand. In this way, every action of the user in the future will not reload the page (that is, no longer ask the server to ask the page for slow HTML, css and js code), but instead use JavaScript to dynamically transform the HTML content (this does not require interaction with the server, unless the data is dynamic, then you only need to ask the server to ask the server for data).

shortcoming
SEO is more difficult.
The first screen loading (first loading) takes a lot of time. In order to realize the single-page web application function and display effect, JavaScript and CSS need to be loaded uniformly when loading the page, and some pages can be loaded when needed. Therefore, JavaScript and CSS code must be merged and compressed;

Pros and cons of multi-page application
advantage
Favorable for SEO.
The first screen loads quickly.

shortcoming
Page switching is slow. Resource sharing (html, css, js) is not shared, not shared, and each page needs to be loaded.
There are many repetitive codes on the page.

Configure multi-page applications

1. Modify

Official website configuration portal

Build the application in multi-page mode. Each "page" should have a corresponding JavaScript entry file. Its value should be an object, the key of the object is the name of the entry, and the value is:

  • An object that specifies entry, template, filename, title and chunks (all optional except entry);
  • Or a string that specifies its entry.
 = {
  pages: {
    index: {
      // The entrance to page      entry: 'src/index/',
      // Template source      template: 'public/',
      // Output in dist/      filename: '',
      // When using the title option,      // The title tag in template needs to be <title><%= %></title>      title: 'Index Page',
      // The blocks included in this page will be included by default      // Extracted general chunk and vendor chunk.      chunks: ['chunk-vendors', 'chunk-common', 'index']
    },
    // When using the entry-only string format,    // The template will be deduced as `public/`    // And if it cannot be found, fall back to `public/`.    // The output file name will be deduced as ``.    subpage: 'src/subpage/'
  }
}

The above is an example from the official website. Here we will rewrite it to configure multiple pages in a unified manner.

Prerequisites Create a new pages folder under src

pages Create the following three files

pages
└── 
└── 
└── 
const glob = require('glob')
const fs = require('fs');
let titleObj = {};
// Unified configuration of multiple pages
// Here is a vue page named under pages under src (for example, index)('./src/pages/**/*').forEach((path) => {
     // traverse path
     (path,'path')
    //./src/pages/index/ path
  
   // Find the file name
   const fileName = ('/')[('/').length - 1];
    (fileName,'fileName')
    // fileName
  
   // Remove the App suffix
   const chunk = (12, ('/' + fileName));
     (chunk,'chunk')
    // index chunk
 
   // Here is to set the title for each page, you need to set a variable pageTitle
   let fileContent = fs
     .readFileSync(path, { encoding: 'utf-8' })
     .toString()
     .replace(/\r\n/g, '');
   fileContent = (('pageTitle:'));
   fileContent = (0, (','));

   fileContent =
     ('"') > 0
       ? (('"') + 1)
       : (("'") + 1);

   fileContent =
     ('"') > 0
       ? (0, ('"'))
       : (0, ("'"));
   titleObj[chunk] = fileContent ? fileContent : 'Title';
 });


 // Here is to traverse the pages below src under each folder (for example, index) under
 ('./src/pages/**/').forEach((path) =&gt; {
  // Package js  const chunk = ('./src/pages/')[1].split('/')[0];
  const tmp = ('/');
  // If the template html is the same, you can use it directly under public. If you want to set the title, you need to have an html template for each page. If you don't need it, you can use the same one to see your personal habits  let templateUrl =
    'src/pages/' + chunk + '/' + tmp[ - 1] + '-';

  pages[chunk] = {
    entry: path,//Entry file    template: templateUrl,//Template html    title: titleObj[chunk] ? titleObj[chunk] : 'title',//title    filename: (/\//g, '-') + '.html',//The packaged html name    chunks: ['chunk-vendors', 'chunk-common', chunk],//Dependency package  };
});
 = {
  // Options...  publicPath: .NODE_ENV === 'production'
    ? '/dist/'
    : '/',
  pages,
}

2. Modify the title

Actually it was replaced with plug-ins

It's very simple, just use the title in the html template to use the template syntax

For example, each page html is the same, just copy it

<title><%=  %></title>

3. Merge third-party libraries

If you do not set up a subcontract, all third-party resource libraries in node_modules, such as Echarts, Axios, ali-oss, etc., will be thrown into chunk-vendors. As for why it is thrown into, let's look at the default subcontracting rules

Official website subcontract splitChunks entrance

Default configuration on the official website

 = {
  //...
 //...
  optimization: {
    splitChunks: {
      chunks: 'async', // When splitting code, it takes effect on asynchronous code. All: all codes are valid, initial: synchronous code is valid      minSize: 30000, // Code segmentation is the smallest module size, and the imported module is greater than 30,000B before code segmentation is performed      maxSize: 0, // The maximum module size of code segmentation is required. If the code is larger than this value, the default value is generally used.      minChunks: 1, // Code segmentation is performed when the number of times introduced is greater than or equal to 1      maxAsyncRequests: 6, // The maximum number of asynchronous requests, that is, the maximum number of modules loaded simultaneously      maxInitialRequests: 4, // The entry file is divided into up to 4 js files for code division      automaticNameDelimiter: '~', // Connector when file generation      automaticNameMaxLength: 30, // Maximum length of automatically generated file names      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/, // The module located in node_modules is used to split the code          priority: -10 // Determine which group to package according to priority, for example, a module in node_modules for code        }, // Split, satisfy both vendors and default, then it will be packaged into the vendors group according to priority.        default: { // No test indicates that all modules can enter the default group, but note that it has a lower priority.          priority: -20, // Determine which group to package into based on priority and package into a group with higher priority.          reuseExistingChunk: true // // If a module has been packaged, then ignore the module when packaging again        }
      }
    }
  }
};

Let's focus on the configuration of minChunks. If the default is greater than 1 time, the subcontracting operation will be performed. In the past, it was a single page, so there was no problem with subcontracting, and it will only be introduced. Now there are multiple pages, and each page will introduce this chunk-vendors. Some packages are actually only used for two or three pages. Therefore, it is best not to subcontract, or to reach a certain number of times to make the subcontract meaning.

We set it here 8 times before subcontracting, and there is almost no subcontracting. You can set it yourself according to your needs

    optimization: {
      minimize: false,
      splitChunks: {
        cacheGroups: {// Cache grouping          common: {// Public module            name: 'chunk-common',//The naming should be consistent with the definition of chunks above            chunks: 'initial',
            minSize: 1,// Size limit            priority: 0,
            minChunks: 8,// At least several times have been reused          },
          // Package third-party library files          vendor: {
            name: 'chunk-vendors',//The naming should be consistent with the definition of chunks above            test: /[\\/]node_modules[\\/]/,
            chunks: 'initial',
            priority: 10,// Higher permissions, priority is given to withdrawal, which is important!  !  !            minChunks: 8,
          },
        },
      },
    },

4. Packaging third-party scss

There are some public scss I wrote myself, for example, I don't want to introduce them on the page, because each page needs to be introduced. In fact, there are also very simple ways to deal with them. This has not changed much from before. Without further ado, just enter the code.

let scssVariables = require('./src/scss/');

css: {
    loaderOptions: {
      scss: {
        prependData:
          (scssVariables)
            .map((k) => `${('_', '-')}: ${scssVariables[k]};`)
            .join('\n') + '\n',
      },
    },
  },

5. Other common settings

Some common settings are just for personal settings. Here I recommend filenameHashing. Multi-page applications do not have hash settings, because there is no route used, so it is not available.

 = {
  publicPath: './',
  //Output directory  outputDir: 'fund',
  assetsDir: '',
  // Configure alias  chainWebpack: (config) =&gt; {
    ('@', resolve('src'));
    ('@@', resolve('src/components'));
    ('@assets', resolve('src/assets'));
    ('scss', resolve('src/scss'));
  },
  // Close eslint verification  lintOnSave: false,
  // No map file generated  productionSourceMap: false,
  //The file name does not have hash value  filenameHashing: false,
  devServer: {
    publicPath: '/fund/',
    proxy: {// Local debugging forward      '/api': {
        target: 'http://127.0.0.1:8080',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '',
        },
      },
    },
  },
};

Summarize

This is the end of this article about vue multi-page project development. For more related vue multi-page project development content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!