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

Basic implementation method of cross-component binding using v-model in Vue

Hello everyone, today we will talk about how to u...

Master-slave synchronous replication configuration of MySQL database under Linux

The advantage of the master-slave synchronization...

CSS 3.0 text hover jump special effects code

Here is a text hovering and jumping effect implem...

JavaScript to achieve a simple message board case

Use Javascript to implement a message board examp...

JavaScript basics of this pointing

Table of contents this Method In the object Hidde...

Install ethereum/Ethereum from scratch under CentOS7

Table of contents Preface Add sudo write permissi...

How to update, package, and upload Docker containers to Alibaba Cloud

This time, we will try to package the running con...

A link refresh page and js refresh page usage examples

1. How to use the link: Copy code The code is as f...

CSS3 achieves flippable hover effect

CSS3 implements a flippable hover effect. The spe...

A must-read career plan for web design practitioners

Original article, please indicate the author and ...

Web page custom selection box Select

Everyone may be familiar with the select drop-dow...

How to create a Django project + connect to MySQL

1: django-admin.py startproject project name 2: c...

Example analysis of mysql user rights management

This article describes the MySQL user rights mana...