Most of the projects built by VUE-CLI are single page application projects. For simple projects, single page can meet the requirements. But for applications with multiple subprojects, if you create multiple single pages, the display can be a bit repetitive, especially if node_modules has multiple copies of the same. If all of them are put into a single page project, it seems a bit messy. At this time, it is a better solution to build a multi-page project by transforming VUe-CLI.

How to modify a single page vue.js project to a multi-page project? Below is the detailed process of this transformation.

Create a single page vue.js project

The scaffolding vuE-CLI3 provided by the authorities is directly used here. For details, please refer to vuE-CLI3.0 Upgrade Record

Two, multi-page configuration

1. Add a configuration file

Add vue.config.js to the project root (in the same directory as package.json) as follows:

module.exports = {
  pages: {
    index: {
      // The path to the entry js
      entry: './src/main'.// Page template path
      template: './src/public/index.html'}}}Copy the code

The above configuration is actually the default configuration of vuE-CLI setup project. If you want to add pages, add the configuration under the Pages node. But this way, every time you add a new page, you need to manually add nodes, which is not smart. Let’s continue with the transformation.

2. Adjust the project structure

To automate, you need to organize your pages according to a rule. For example, if all routing pages are placed in the SRC /pages directory, the modified structure is as follows:

3. Write automatic configuration files

Add vue.util.js to the project root (same directory as package.json) as follows:

const path = require('path')
const glob = require('glob')
const START_PATH = '/src/pages/'
const PAGE_PATH = path.resolve(__dirname, '. ' + START_PATH)

exports.pages = function () {
  var entryFiles = glob.sync(PAGE_PATH + '/**/*.html')
  var obj = {}
  entryFiles.forEach((filePath) = > {
    var dirPath = filePath.substring(0, filePath.lastIndexOf('/'))
    var dirName = dirPath.substring(dirPath.lastIndexOf('/') + 1)
    var filename = filePath.substring(filePath.lastIndexOf(START_PATH) + START_PATH.length, filePath.lastIndexOf('/'))
    if (filename.endsWith(dirName)) {
      obj[filename] = {
        entry: filePath.substring(0, filePath.lastIndexOf('.html')) + '.js'.template: filePath.substring(0, filePath.lastIndexOf('.html')) + '.html'}}})return obj
}
Copy the code

Use the above configuration in vue.config.js

const utils = require('./vue.util')

module.exports = {
  pages: utils.pages()
}
Copy the code

Three, test

yarn dev
Copy the code

Browser input:

http://localhost:8080/index.html and http://localhost:8080/index2.html

OK, the multi-page configuration is complete