vue多页面应用的动态配置

vue结合webpack构建多页面应用时,若一个个页面配置显然过于繁琐。这里我们以示例介绍下多页面应用如何实现动态配置。

一:src目录下建pages文件夹,将所有页面放在pages目录下

vue多页面应用的动态配置_第1张图片

二、创建scanner.js文件,用于动态遍历pages子目录,以获取entry入口文件对象 和 html-webpack-plugin实例数组

遍历pages目录下的所有孙辈js和html,以其父目录(即pages子目录)命名js和html。

scanner.js文件

const path = require('path')
const glob = require('glob')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const PAGE_PATH = path.resolve(__dirname, '../src/pages')
const merge = require('webpack-merge')

const baseDir = filePath => path.basename(path.dirname(filePath))

exports.entries = () => {
    var entryFiles = glob.sync(PAGE_PATH + '/*/*.js')
    var map = {}
    entryFiles.forEach((filePath) => {
        var filename = baseDir(filePath)
        map[filename] = filePath
    })
    return map
}

exports.htmlPlugin = () => {
    let entryHtml = glob.sync(PAGE_PATH + '/*/*.html')
    let arr = []
    console.log('扫描到如下模块:')
    entryHtml.forEach((filePath) => {
        console.log(`\t${baseDir(filePath)} => ${filePath}`)
        var filename = baseDir(filePath)
        let conf = {
            template: filePath,
            filename: filename + '.html',
            chunks: ['manifest', 'vendor', filename],
            inject: true
        }
        if (process.env.NODE_ENV === 'production') {
            conf = merge(conf, {
                minify: {
                    removeComments: true,
                    collapseWhitespace: true,
                    removeAttributeQuotes: true
                },
                chunksSortMode: 'dependency'
            })
        }
        arr.push(new HtmlWebpackPlugin(conf))
    })
    return arr
}

三、配置webpack配置文件

1)配置webpack.base.conf.js文件
打开webpack.base.conf.js文件,引入scanner.js文件中的entries方法,配置entry入口文件。
vue多页面应用的动态配置_第2张图片
2)配置webpack.dev.conf.js和webpack.prod.conf.js文件

// 引入scanner.js文件的htmlPlugin方法
const {htmlPlugin} = require('./scanner')

// 将htmlPlugin方法生成的html-webpack-plugin实例数组合并至plugins数组中
plugins:[
	...
].concat(htmlPlugin())

vue多页面应用的动态配置_第3张图片

你可能感兴趣的:(vue)