前言: 本文基于vue 2.5.2, webpack 3.6.0(配置多页面原理类似,实现方法各有千秋,可根据需要进行定制化)

vue 是单页面应用。但是在做大型项目时,单页面往往无法满足我们的需求,因此需要配置多页面应用。

Vue多页面应用开发

1. 新建 vue 项目


vue init webpack vue_multiple_test
cd vue_multiple_test
npm install

2. 安装 glob


npm i glob --save-dev

glob 模块用于查找符合要求的文件

3. 目标结构目录


.
├── README.md
├── build
│   ├── build.js
│   ├── check-versions.js
│   ├── logo.png
│   ├── utils.js
│   ├── vue-loader.conf.js
│   ├── webpack.base.conf.js
│   ├── webpack.dev.conf.js
│   └── webpack.prod.conf.js
├── config
│   ├── dev.env.js
│   ├── index.js
│   └── prod.env.js
├── generatePage.sh
├── index.html
├── package-lock.json
├── package.json
├── src
│   ├── assets
│   │   └── logo.png
│   └── pages
│   ├── page1
│   │   ├── App.vue
│   │   ├── index.html
│   │   └── index.js
│   └── page2
│   ├── App.vue
│   ├── index.html
│   └── index.js
└── static

其中,pages文件夹用于放置页面。 page1page2用于分别放置不同页面,且默认均包含三个文档: App.vue, index.html, index.js, 这样在多人协作时,可以更为清晰地明确每个文件的含义。除此之外,此文件也可配置路由。

4. utils 增加下述代码:


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

其中:PAGE_PATH 为所有页面所在的文件夹路径,指向 pages文件夹。


exports.entries = function () {
/*用于匹配 pages 下一级文件夹中的 index.js 文件 */
var entryFiles = glob.sync(PAGE_PATH + '/*/index.js')
var map = {}
entryFiles.forEach((filePath) => {
/* 下述两句代码用于取出 pages 下一级文件夹的名称 */
var entryPath = path.dirname(filePath)
var filename = entryPath.substring(entryPath.lastIndexOf('\/') + 1)
/* 生成对应的键值对 */
map[filename] = filePath
})
return map
}

该方法用于生成多页面的入口对象,例如本例,获得的入口对象如下:


{
page1: '/Users/work/learn/vue/vue_multiple_test/src/pages/page1/index.js',
page2: '/Users/work/learn/vue/vue_multiple_test/src/pages/page2/index.js',
}

其中:key 为当前页面的文件夹名称, value 为当前页面的入口文件名称


exports.htmlPlugin = function () {
let entryHtml = glob.sync(PAGE_PATH + '/*/index.html')
let arr = []
entryHtml.forEach((filePath) => {
var entryPath = path.dirname(filePath)
var filename = entryPath.substring(entryPath.lastIndexOf('\/') + 1)
let conf = {
template: filePath,
filename: filename + `/index.html`,
chunks: ['manifest', 'vendor', filename],
inject: true
}
if (process.env.NODE_ENV === 'production') {
let productionConfig = {
minify: {
removeComments: true, // 移除注释
collapseWhitespace: true, // 删除空白符和换行符
removeAttributeQuotes: true // 移除属性引号
},
chunksSortMode: 'dependency' // 对引入的chunk模块进行排序
}
conf = {...conf, ...productionConfig} //合并基础配置和生产环境专属配置
}
arr.push(new HtmlWebpackPlugin(conf))
})
return arr
}

4. webpack.base.conf.js修改入口如下:


entry: utils.entries()

5. webpack.dev.conf.js

devWebpackConfig 中的 plugins数组后面拼接上上面新写的htmlPlugin:


plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
].concat(utils.htmlPlugin())

并删除下述代码:


new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})

6. webpack.prod.conf.js

webpack.dev.conf.js 中的类似处理:


plugins: [
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
allChunks: true,
}),
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
new webpack.HashedModuleIdsPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
].concat(utils.htmlPlugin())

并删除下述代码:


new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunksSortMode: 'dependency'
})

7. 构建结果


【dev】开发环境下,执行 npm run dev 访问: http://localhost:8080/page1/index.html
http://localhost:8080/page2/index.html 即为访问不同的页面 【production】生产环境下,执行 npm run build, 生成的文件目录如下所示: │ ├── dist
│   ├── page1
│   │   └── index.html
│   ├── page2
│   │   └── index.html
│   └── static
│   ├── css
│   │   ├── page1.86a4513a3e04c0dcb73e6d6aea4580e4.css
│   │   ├── page1.86a4513a3e04c0dcb73e6d6aea4580e4.css.map
│   │   ├── page2.86a4513a3e04c0dcb73e6d6aea4580e4.css
│   │   └── page2.86a4513a3e04c0dcb73e6d6aea4580e4.css.map
│   └── js
│   ├── manifest.0c1cd46d93b12dcd0191.js
│   ├── manifest.0c1cd46d93b12dcd0191.js.map
│   ├── page1.e2997955f3b0f2090b7a.js
│   ├── page1.e2997955f3b0f2090b7a.js.map
│   ├── page2.4d41f3b684a56847f057.js
│   ├── page2.4d41f3b684a56847f057.js.map
│   ├── vendor.bb335a033c3b9e5d296a.js
│   └── vendor.bb335a033c3b9e5d296a.js.map

8.【懒人福利】使用shell脚本自动构建基础页面

在项目文件下新建shell脚本generatePage.sh, 并在脚本中写入下述代码:


#!/bin/bash
# 打开 pages 文件夹,并创建文件
cd src/pages
for file in $(ls)
do
if [ $file == $1 ];then
echo $1' 文件已存在, 请使用其他名字'
exit
fi
done
mkdir $1
cd $1
# 生成 index.html
echo "" > index.html
echo '<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title></title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>' > index.html # 生成 App.vue
echo "" > App.vue
echo '<template>
<div id="app">
</div>
</template> <script>
export default {
name: "App"
}
</script> <style>
#app {}
</style>' > App.vue # 生成 index.js
echo "" > index.js
echo "import Vue from 'vue'
import App from './App' Vue.config.productionTip = false /* eslint-disable no-new */
new Vue({
el: '#app',
components: { App },
template: '<App/>'
})" > index.js

之后在项目路径下输入下述命令:


bash generatePage.sh page4

即可在pages文件夹下生成一个名为page4的新页面。还可以通过自定义shell脚本的内容写入路由等,以实现定制需求。

原文地址:https://segmentfault.com/a/1190000016758185

vue 配置多页面应用的更多相关文章

  1. vue配置404页面

    { path:'*', name:"/404", component:cuowu } path星号表示没有这个路由 name表示去这个地址 component这个页面引入的时候叫的 ...

  2. vue实现部分页面导入底部 vue配置公用头部、底部,可控制显示隐藏

    vue实现部分页面导入底部 vue配置公用头部.底部,可控制显示隐藏 在app.vue文件里引入公共的header 和 footer header 和 footer 默认显示,例如某个页面不需要显示h ...

  3. 066——VUE中vue-router之rewrite模式下配置404页面

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. vue搭建多页面开发环境

    自从习惯开发了单页面应用,对多页面的页面间的相互跳转间没有过渡效果.难维护极度反感.但是最近公司技术老大说,当一个应用越来越大的时候单页面模式应付不来,但是没讲怎么应付不来,所以还得自己去复习一遍这两 ...

  5. 【vue】使用vue构建多页面应用

    先了解一些单页面和多页面的区别 mm 多页应用模式MPA 单页应用模式SPA 应用构成 由多个完整页面构成 一个外壳页面和多个页面片段构成 跳转方式 页面之间的跳转是从一个页面跳转到另一个页面 页面片 ...

  6. 高性能流媒体服务器EasyDSS前端重构(一)-从零开始搭建 webpack + vue + AdminLTE 多页面脚手架

    本文围绕着实现EasyDSS高性能流媒体服务器的前端框架来展开的,具体EasyDSS的相关信息可在:www.easydss.com 找到! EasyDSS 高性能流媒体服务器前端架构概述 EasyDS ...

  7. vue使用nprogress页面加载进度条

    vue使用nprogress页面加载进度条 NProgress是页面跳转是出现在浏览器顶部的进度条 官网:http://ricostacruz.com/nprogress/ github:https: ...

  8. 高性能流媒体服务器EasyDSS前端重构(三)- webpack + vue + AdminLTE 多页面引入 element-ui

    接上篇 接上篇<高性能流媒体服务器EasyDSS前端重构(二) webpack + vue + AdminLTE 多页面提取共用文件, 优化编译时间> 本文围绕着实现EasyDSS高性能流 ...

  9. 高性能流媒体服务器EasyDSS前端重构(二) webpack + vue + AdminLTE 多页面提取共用文件, 优化编译时间

    本文围绕着实现EasyDSS高性能流媒体服务器的前端框架来展开的,具体EasyDSS的相关信息可在:www.easydss.com 找到! 接上回 <高性能流媒体服务器EasyDSS前端重构(一 ...

随机推荐

  1. [Java]LinkedHashMap实现原理

    1.概述 在理解了#7 介绍的HashMap后,我们来学习LinkedHashMap的工作原理及实现.首先还是类似的,我们写一个简单的LinkedHashMap的程序: LinkedHashMap&l ...

  2. [Android]解决 Could not read entry xxx from cache taskArtifacts.bin

    Bug 出现 事情是这样的,昨天早晨我正做着项目,坐在我旁边的小伙伴呼唤了我一下,说项目运行不起来了. 我纳闷着,前天的时候还好好的,怎么过了一晚就出问题了.我问他是不是改了什么配置,或者添加了什么东 ...

  3. Codecraft-17 and Codeforces Round #391 (Div. 1 + Div. 2, combined) C

    It's that time of the year, Felicity is around the corner and you can see people celebrating all aro ...

  4. Debian 跨版本升级

    相对于某些重量级 Linux 发行版而言,同样是通过网络跨版本升级,Debian 的升级过程总要显得轻快很多.不会因为要下载数量惊人的软件包并安装而把升级时间拉得很长,也不用担心中途某些程序崩溃退出导 ...

  5. 关于使用rancher部署k8s集群的一些小问题的解决

    问题一: 在rancher的ui上,不能创建k8s的master节点的高可用集群.创建k8s集群,添加节点的时候,可以添加多个master,但是多个master又没有高可用,只要其中一个出问题了,那么 ...

  6. Hart协议

    官方https://fieldcommgroup.org/technologies/hart/documents-and-downloads-hart 参考网页http://www.eeworld.c ...

  7. logback-spring.xml

    <?xml version="1.0" encoding="UTF-8"?><!--该日志将日志级别不同的log信息保存到不同的文件中--&g ...

  8. css position 定位模式

     定位 定位模式: static relative absolute fixed 边偏移 :top bottom left right 一般的定位必须要有定位模式以及边偏移 static 静态定位 默 ...

  9. arcgis jsapi接口入门系列(0):总览

    开发环境: arcgis jsapi版本4.9 由于我们这套代码是基于vue,webpack开发的,会有少数vue代码,但总体不影响 里面还有些我们公司的js库和html css,给出的代码不能百分百 ...

  10. iOS VIPER架构(一)

    洋葱模型 洋葱模型,是从冰山模型上演变而来的,用来进行层次分析的模型,这是Redux的洋葱模型. action从最外层传入,层层传递直至核心后,经过逐层事件触发,再次被分发出来,执行后续操作. 洋葱模 ...