VUE.CLI4.0配置多页面入口的实现
为何需要配置多页面?
在实际工作中,肯定会遇到大型项目,往往一个架构里面会开发多个应用,而这些应用又没有太大的关联,但有可能会共用一些组件或者是样式表等,那么就会出现一个问题,打包的时候会将这些互不相关的应用全部打包。
而因为脚手架VueCli所以构建的项目属于单页面应用,因此我们就需要手动去配置,搭建一个多入口,多应用的体系
需求
首页显示各个应用名称,点击进去各自应用
实现
使用vue/cli生成一个vue项目
npminstall-g@vue/cli个人不建议直接全局安装,因为可能会对其他项目造成影响,所以会选择加上-D来进行本地安装
然后vuecreateproject-name(使用本地安装的记得加上npx)
成功创建之后,我们看看当前的目录结构
这里我们需要重构一下我们的目录让他更可观
配置vue.config.js
letpath=require('path') letglob=require('glob')//用于筛选文件 //工厂函数-配置pages实现多页面获取某文件夹下的html与js functionhandleEntry(entry){ letentries={} letentryBaseName='' letentryPathName='' letentryTemplate='' letapplicationName='' glob.sync(entry).forEach(item=>{ console.log('!!!',item) entryBaseName=path.basename(item,path.extname(item)) console.log('entryBaseName:',entryBaseName) entryTemplate=item.split('/').splice(-3) console.log('entryTemplate:',entryTemplate) entryPathName=entryBaseName//正确输出js和html的路径 console.log('entryPathName',entryPathName) entries[entryPathName]={ entry:'src/'+entryTemplate[0]+'/'+entryTemplate[1]+'/'+entryTemplate[1]+'.js', template:'src/'+entryTemplate[0]+'/'+entryTemplate[1]+'/'+entryTemplate[2], title:entryTemplate[2], filename:entryTemplate[2] } }) returnentries } letpages=handleEntry('./src/applications/**?/*.html') console.log(pages) //以下开始配置 module.exports={ lintOnSave:false,//关掉eslint /** *baseUrl从3.3起废用,使用pubilcPath代替 *默认情况下,VueCLI会假设你的应用是被部署在一个域名的根路径上,例如https://www.my-app.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在https://www.my-app.com/my-app/,则设置publicPath为/my-app/。 *这个值也可以被设置为空字符串('')或是相对路径('./'),这样所有的资源都会被链接为相对路径,这样打出来的包可以被部署在任意路径,也可以用在类似Cordovahybrid应用的文件系统中。 */ publicPath:process.env.NODE_ENV==="production"?"./":"/", productionSourceMap:false, //入口设置 pages, devServer:{ index:'/',//运行时,默认打开application1页面 //告诉dev-server在服务器启动后打开浏览器,将其设置true为打开默认浏览器 open:true, host:'localhost', port:8080, https:false, hotOnly:false, //配置首页入口链接 before:app=>{ app.get('/',(req,res,next)=>{ for(letiinpages){ res.write(`/${i}`); } res.end() }); } } }
application1.js importVuefrom'vue' importApplication1from'./application1.vue' importrouterfrom'./router' importstorefrom'./vuex' Vue.config.productionTip=false newVue({ router, store, render:h=>h(Application1) }).$mount('#app')
application1.vueHelloImApplication1,ClikemecangotoApplication2
application1.htmlfavicon.ico"> Application1