vue 配置多頁面應用的示例程式碼
前言: 本文基於vue 2.5.2, webpack 3.6.0(配置多頁面原理類似,實現方法各有千秋,可根據需要進行定製化)
vue 是單頁面應用。但是在做大型專案時,單頁面往往無法滿足我們的需求,因此需要配置多頁面應用。
-
新建 vue 專案
vue init webpack vue_multiple_test
cd vue_multiple_test
npm install
-
安裝 glob
npm i glob --save-dev
glob 模組用於查詢符合要求的檔案
-
目標結構目錄
.
├── 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資料夾用於放置頁面。 page1 和 page2用於分別放置不同頁面,且預設均包含三個文件: App.vue, index.html, index.js, 這樣在多人協作時,可以更為清晰地明確每個檔案的含義。除此之外,此檔案也可配置路由。
-
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 () {
/
/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
}
- webpack.base.conf.js修改入口如下:
entry: utils.entries() - 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
})
-
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'
})
-
構建結果
【dev】開發環境下,執行 npm run dev 訪問:
即為訪問不同的頁面
【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 in1' 檔案已存在, 請使用其他名字'
exit
fi
done
mkdir1
生成 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>
</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指令碼的內容寫入路由等,以實現定製需求。
最後
為了幫助大家讓學習變得輕鬆、高效,給大家免費分享一大批資料,幫助大家在成為全棧工程師,乃至架構師的路上披荊斬棘。在這裡給大家推薦一個前端全棧學習交流圈: 866109386 .歡迎大家進群交流討論,學習交流,共同進步。
當真正開始學習的時候難免不知道從哪入手,導致效率低下影響繼續學習的信心。
但最重要的是不知道哪些技術需要重點掌握,學習時頻繁踩坑,最終浪費大量時間,所以有有效資源還是很有必要的。
最後祝福所有遇到瓶疾且不知道怎麼辦的前端程式設計師們,祝福大家在往後的工作與面試中一切順利。

.png