Vue-CLI multi-page directory packaging steps record

Vue-CLI multi-page directory packaging steps record

Page directory structure

Note that you need to move the default HTML template file public/index.html to the root directory.

Install Dependencies

npm i --save-dev cross-env tasksfile

build/pages.js

Get the multi-page object required by Vue CLI

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

const isProduction = process.env.NODE_ENV === 'production'

// Customize page titles for different modules
const titleMap = {
  index: 'Home'
}

function getPages (globPath) {
  const pages = {}
  glob.sync(globPath).forEach((item) => {
    const stats = fs.statSync(item)
    if (stats.isDirectory()) {
      const basename = path.basename(item, path.extname(item))

      // If there is index.html in the module directory, use that file as the html template file const template = fs.existsSync(`${item}/index.html`)
        ? `${item}/index.html`
        : path.join(__dirname, '../index.html')

      pages[basename] = {
        entry: `${item}/main.js`,
        title: titleMap[basename] || 'Default page',
        template,
        // This line of code is very important // Compatible with development and production. The html page hierarchy is consistent filename: isProduction ? 'index.html' : `${basename}/index.html`
      }
    }
  })
  return pages
}

const pages = getPages(path.join(__dirname, '../src/pages/*'))

module.exports = pages

build/index.js

Execute the build command and loop vue-cli-service build.

const chalk = require('chalk')
const rimraf = require('rimraf')
const { sh } = require('tasksfile')

const PAGES = require('./pages')

// vue-cli-service --mode value const mode = process.env.MODE || 'prod'

// Module name, may be multiple const moduleNames = process.argv[2]

// List of all pages const pageList = Object.keys(PAGES)

// If the valid module list is not specified, it will be the list of all pages const validPageList = moduleNames ? moduleNames.split(',').filter((item) => pageList.includes(item)) : pageList
if (!validPageList.length) {
  console.log(chalk.red('**Module name is incorrect**'))
  return
}

console.log(chalk.blue(`Valid module:${validPageList.join(',')}`))

// Delete the dist directory rimraf.sync('dist')

console.time('total compilation time')
const count = validPageList.length
let current = 0
// Execute module compilation one by one for (let i = 0; i < validPageList.length; i += 1) {
  const moduleName = validPageList[i]
  process.env.MODULE_NAME = moduleName

  console.log(chalk.blue(`${moduleName} module started compiling`))

  // Compile via vue-cli-service build sh(`vue-cli-service build --mode ${mode}`, { async: true }).then(() => {
    console.log(chalk.blue(`${moduleName} module compilation completed`))
    console.log()
    current += 1
    if (current === count) {
      console.log(chalk.blue('-----All modules compiled-----'))
      console.timeEnd('total compilation time')
    }
  })
}

build/dev-modules.js

Customize the module that needs to be compiled for local development. The module name is the folder name under src/pages.

// Modules that need to be compiled for local development module.exports = [

]

vue.config.js

const chalk = require('chalk')

const devModuleList = require('./build/dev-modules')

const isProduction = process.env.NODE_ENV === 'production'

//Total pages const PAGES = require('./build/pages')

for (const basename in PAGES) {
  if (Object.prototype.hasOwnProperty.call(PAGES, basename)) {
    PAGES[basename].chunks = [
      'chunk-vue',
      'chunk-vendors',
      'chunk-common',
      `${basename}`
    ]
  }
}

let pages = {}
const moduleName = process.env.MODULE_NAME

if (isProduction) {
  // Construct the name of the module if (!PAGES[moduleName]) {
    console.log(chalk.red('**Module name is incorrect**'))
    return
  }
  pages[moduleName] = PAGES[moduleName]
} else {
  // Local development compiled module // Compile all if (process.env.DEV_MODULE === 'all') {
    pages = PAGES
  } else {
    // Compile some modules const moduleList = [
      // Fixed compiled module 'index',
      'login',
      // Custom compiled modules...devModuleList
    ]
    moduleList.forEach(item => {
      pages[item] = PAGES[item]
    })
  }
}

module.exports = {
  // This line of code is very important publicPath: isProduction ? './' : '/',
  pages,
  // This line of code is very important outputDir: isProduction ? `dist/${moduleName}` : 'dist',
  productionSourceMap: false,
  css: {
    loaderOptions: {
      sass: {
        prependData: '@import "~@/styles/variables.scss";'
      }
    }
  },
  chainWebpack: (config) => {
    config.optimization.splitChunks({
      cacheGroups:
        vue: {
          name: 'chunk-vue',
          test: /[\\/]node_modules[\\/]_?(vue|vue-router|vuex|element-ui)(@.*)?[\\/]/,
          priority: -1,
          chunks: 'initial'
        },
        vendors:
          name: 'chunk-vendors',
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
          chunks: 'initial'
        },
        common:
          name: 'chunk-common',
          minChunks: 2,
          priority: -20,
          chunks: 'initial',
          reuseExistingChunk: true
        }
      }
    })
  }
}

package.json

{
  "scripts": {
    "serve": "vue-cli-service serve",
    "serve:all": "cross-env DEV_MODULE=all vue-cli-service serve",
    "build:test": "cross-env MODE=test node build/index.js",
    "build:prod": "cross-env MODE=prod node build/index.js",
    "lint": "vue-cli-service lint",
  }
}

Local Development

When developing locally, npm run serve will compile a custom module directory, and npm run serve:all will compile all module directories.

The directory structure after compilation during local development is as follows:

So after startup, you need to change the address to http://localhost:8080/index/index.html.

Packaging results

When building, npm run build:prod packages all pages, and npm run build:prod index only packages the index page.

The packaged directory structure is as follows:

In this way, when jumping between different modules, you can use a consistent relative path jump method, ../index/index.html .

After packaging, the contents of each module are packaged into a separate directory.

Github address

Summarize

This is the end of this article about Vue-CLI multi-page directory packaging. For more relevant Vue-CLI multi-page directory packaging content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • About vue-cli 3 configuration packaging optimization points (recommended)
  • Detailed explanation of vue-cli3 multi-environment packaging configuration
  • Solve the problem of vendor files being too large after vue-cli scaffolding packaging
  • The pitfalls of using HBuilderx to package app in vue-cli
  • How to use electron to package the vue-cli project into exe
  • Solution to the error in the packaged image path in vue-cli
  • An example of how to package and launch vue-cli
  • Example of vue-cli3 environment variables and environment packaging

<<:  Ideas and methods for incremental backup of MySQL database

>>:  MySQL slow query log configuration and usage tutorial

Recommend

How to optimize images to improve website performance

Table of contents Overview What is Image Compress...

MySQL UNION operator basic knowledge points

MySQL UNION Operator This tutorial introduces the...

Detailed explanation of mysql download and installation process

1: Download MySql Official website download addre...

HTML/CSS Basics - Several precautions in HTML code writing (must read)

The warning points in this article have nothing t...

Detailed explanation of rpm installation in mysql

View installation and uninstallation # View rpm -...

Summary of MySQL development standards and usage skills

1. Naming conventions 1. Database names, table na...

Docker deploys Mysql, .Net6, Sqlserver and other containers

Table of contents Install Docker on CentOS 8 1. U...

Introduction to the process of building your own FTP and SFTP servers

FTP and SFTP are widely used as file transfer pro...

IIS and APACHE implement HTTP redirection to HTTPS

IIS7 Download the HTTP Rewrite module from Micros...

jQuery implements the bouncing ball game

This article shares the specific code of jQuery t...

Detailed explanation of the steps of using ElementUI in actual projects

Table of contents 1. Table self-sorting 2. Paging...

The difference between Vue interpolation expression and v-text directive

Table of contents 1. Use plugin expressions 2. Us...

Detailed explanation of how to view the number of MySQL server threads

This article uses an example to describe how to v...