- 生成vue3的项目
vue create pagesdemo
2.在src文件中添加pages文件夹,同时删除app.vue main.js 在pages下添加项目文件夹,里面的目录结构和 原src一致。如下图
3. 配置vue.config.js
vue-cli提供了pags参数,可以使用这个参数进行多页面配置,不过我们希望自动引入pages下的所有项目就要重新提供一个方法,获取pages下的文件夹名称和webpack的入口。
const path = require('path')
const fs = require('fs')
function getPages (pageName) {const map = {}if (!pageName) {const PAGE_PATH = path.resolve(__dirname, './src/pages')const entryFiles = fs.readdirSync(PAGE_PATH)entryFiles.forEach(filePath => {map[filePath] = {entry: 'src/pages/' + filePath + '/main.js',template: 'public/index.html',filename: filePath + '/' + filePath + '.html',chunks: ['chunk-vendors', 'chunk-common', filePath]}})return map}// 指定单页面打包map[pageName] = {entry: 'src/pages/' + pageName + '/main.js',template: 'public/index.html',filename: pageName + '/' + pageName + '.html',chunks: ['chunk-vendors', 'chunk-common', pageName]}return map
}
console.log(process.env.NODE_ENV)
const rawArgv = process.argv.slice(2)
const [, , moduleName] = rawArgv
const pages = getPages(moduleName)
module.exports = {pages: pages,outputDir: 'dist',assetsDir: 'common',productionSourceMap: false, // 打包不生成mapchainWebpack: config => {config.output.filename(() => {return '[name]/js/[name].js'})config.plugin('extract-css').tap(options => {options[0].filename = '[name]/css/[name].[hash:8].css'return options})// 使用splitChunks抽离公用代码config.optimization.splitChunks({cacheGroups: {common: {name: 'chunk-common', // 打包后的文件名chunks: 'initial', //minChunks: 2,maxInitialRequests: 5,minSize: 0,priority: 1,reuseExistingChunk: true},vendors: {name: 'chunk-vendors',test: /[\\/]node_modules[\\/]/,chunks: 'initial',priority: 2,reuseExistingChunk: true,enforce: true}}})},configureWebpack: {},css: {extract: true,requireModuleExtension: true,sourceMap: false}
}
上面getPages 方法生成的pages如下
{client: {entry: 'src/pages/client/main.js',template: 'public/index.html',filename: 'client/client.html',chunks: [ 'chunk-vendors', 'chunk-common', 'client' ]},console: {entry: 'src/pages/console/main.js',template: 'public/index.html',filename: 'console/console.html',chunks: [ 'chunk-vendors', 'chunk-common', 'console' ]}
}
4.运行项目 yarn serve
http://localhost:8080/console.html
http://localhost:8080/client.html
查看效果。