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

Reasons and solutions for MySQL selecting the wrong index

In MySQL, you can specify multiple indexes for a ...

A Deep Dive into the MySQL InnoDB Storage Engine

Preface In MySQL, InnoDB belongs to the storage e...

Usage and description of HTML tag tbody

The tbody element should be used in conjunction wi...

MySQL time types and modes details

Table of contents 1. MySQL time type 2. Check the...

Use tomcat to set shared lib to share the same jar

As more and more projects are deployed, more and ...

Detailed explanation of InnoDB storage files in MySQL

Physically speaking, an InnoDB table consists of ...

Comparison of the efficiency of different methods of deleting files in Linux

Test the efficiency of deleting a large number of...

Detailed explanation of MySQL semi-synchronization

Table of contents Preface MySQL master-slave repl...

How to install golang under linux

Go is an open source programming language that ma...

Example code for making the pre tag automatically wrap

The pre element defines preformatted text. Text en...

Node.js uses express-fileupload middleware to upload files

Table of contents Initialize the project Writing ...

This article teaches you how to play with CSS combination selectors

CSS combination selectors include various combina...