详解vue-cli多页面工程实践

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

详解vue-cli多页面工程实践

水木酱   2020-05-16 我要评论

本文介绍了vue-cli多页面工程实践,分享给大家,具体如下:

src目录结构

因为是自定义的设置,src下的目录结构需要固定,约定大于配置嘛。

src目录结构:

src/
 components/
 modules/   # 多页面
  index/   # index 单页面
   index.html
   main.js # 入口文件
  page1/
   index.html
   main.js
  group/
   page2/
    index.html
    main.js

build中的配置

utils.js 增加:

// match files
let glob = require('glob');

/**
 * globPath 获取泛路径下的特定文件
 */
exports.getEntities = function (path) {
 let entities = {};
 glob.sync(path).forEach(function (entity) {
  let moduleName = entity.split('/').slice(-2,-1);
  entities[moduleName] = entity
 });
 // eg: { main: './src/module/index/main.js', test: './src/module/group/test/main.js' }
 return entities;
};

webpack.base.conf.js 修改输入和输出:

module.exports = {
 // 遍历获取入口文件
 entry: utils.getEntities("./src/modules/**/main.js"),
 ...
 plugins:[]
};
/***
 * 生成 <module>/index.html
 */
let utils = require('./utils')
let pages = utils.getEntities("./src/modules/**/index.html");
for (let page in pages) {
 let filename = "index.html";
 if(page!=='index'){
  filename = page+"/index.html";
 }
 module.exports.plugins.push(new HtmlWebpackPlugin({
  filename: filename,
  template: pages,
  inject: true,
  minify: {
   removeComments: true,
   collapseWhitespace: true,
   removeAttributeQuotes: true
   // more options:
   // https://github.com/kangax/html-minifier#options-quick-reference
  },
  // necessary to consistently work with multiple chunks via CommonsChunkPlugin
  chunksSortMode: 'dependency',
  chunks: ['manifest','vendor',page]
 }));
}

同时,webpack.dev.conf.js和webpack.prod.conf.js中的HtmlWebpackPlugin删除。

这时,访问localhost:8080/和localhost:8080/page1即可看到效果。

vue-router history模式下的多页面支持

vue-router history模式需要web server支持,这里演示dev环境下的express支持多页面的history模式。

buildhttps://img.qb5200.com/download-x/dev-server.js 在原来require('connect-history-api-fallback')地方修改:

// handle fallback for HTML5 history API
// rewrite的时候注意 js文件也会被rewrite
let utils = require("./utils");
let history = require('connect-history-api-fallback');
let pages = utils.getEntities("./src/modules/**/index.html");
let rewrites = [];
for(let page in pages){
 // match: /page/* or /page
 rewrites.push({from: new RegExp('\/'+page+'\/|^\/'+page+'$'), to: '/'+page+'/index.html'})
}
app.use(history({
 rewrites: rewrites
}));

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们