vue-cli多頁面工程實踐

模板工程-githubjavascript

src目錄結構

由於是自定義的設置,src下的目錄結構須要固定,約定大於配置嘛。html

src目錄結構:vue

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

build中的配置

utils.js 增長:java

// 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 修改輸入和輸出:webpack

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[page],
    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刪除。git

這時,訪問localhost:8080/和localhost:8080/page1便可看到效果。github

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

vue-router history模式須要web server支持,這裏演示dev環境下的express支持多頁面的history模式。web

build/dev-server.js 在原來require('connect-history-api-fallback')地方修改:vue-router

// 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
}));
相關文章
相關標籤/搜索