基于vue-cli3的自動化多頁面模板,在網(wǎng)上資源文章及自己需求的推動下,可以各頁面獨立資源分文件夾編譯和原生所有資源統(tǒng)一編譯.
正文
大家可以直接使用我改好的初始模板.
自己搭建
- 創(chuàng)建自動化腳本
在項目根目錄創(chuàng)建script文件夾,里面創(chuàng)建兩個文件splitBuild.js
和getPages.js
.
getPages.js
// getPages.js 自動獲取目錄結(jié)構(gòu)
const glob = require('glob')
let pages = {}
module.exports.pages = function () {
glob.sync('./src/pages/*/*.js').forEach(filepath => {
let fileList = filepath.split('/')
let fileName = fileList[fileList.length - 2]
pages[fileName] = {
entry: `src/pages/${fileName}/${fileName}.js`,
// 模板來源
template: `src/pages/${fileName}/${fileName}.html`,
// 在 dist/index.html 的輸出
filename: process.env.VUE_APP_TITLE !== 'ps' ? `${fileName}.html` : `${fileName}/${fileName}.html`,
// 提取出來的通用 chunk 和 vendor chunk号涯。
chunks: ['chunk-vendors', 'chunk-common', fileName]
}
})
return pages
}
splitBuild.js
// splitBuild.js 分開編譯資源處理腳本
var fs = require('fs')
const glob = require('glob')
const config = require('../vue.config.js')
const publicPath = config.publicPath || ''
const outputDir = config.outputDir || 'dist'
/**
* js文件copy
* @param src
* @param dst
*/
var callbackFileJs = function (src, dst) {
fs.readFile(src, 'utf8', function (error, data) {
if (error) {
// eslint-disable-next-line no-console
console.log(error)
return false
}
fs.writeFile(dst, data.toString(), 'utf8', function (error) {
if (error) {
// eslint-disable-next-line no-console
console.log(error)
return false
}
if (dst.includes('.map')) {
// let srcName = src.split('/')[4]
// fs.unlink(`./${outputDir}/js/${srcName}.map`,function () { // 刪除map
// })
// fs.unlink(`./${outputDir}/js/${srcName}`,function () { // 刪除js
// })
} else { // JS寫入成功
callbackFileJs(dst, `${dst}.map`)
}
})
})
}
// 復(fù)制目錄
glob.sync(`./${outputDir}/js/*.js`).forEach((filepath, name) => {
let fileNameList = filepath.split('.')
let fileName = fileNameList[1].split('/')[3]// 多頁面頁面目錄
let copyName = filepath.split('/')[3]
let changeDirectory = `./${outputDir}/${fileName}/js`// 多頁面JS文件地存放址
if (!fileName.includes('chunk-')) {
// eslint-disable-next-line
fs.exists(changeDirectory, function (exists) {
if (exists) {
// console.log(`${fileName}下JS文件已經(jīng)存在`)
callbackFileJs(filepath, `${changeDirectory}/${copyName}`)
} else {
fs.mkdir(changeDirectory, function () {
callbackFileJs(filepath, `${changeDirectory}/${copyName}`)
// console.log(`${fileName}下JS文件創(chuàng)建成功`)
})
}
})
}
})
/**
* css文件拷貝
* @param src
* @param dst
*/
var callbackFileCss = function (src, dst) {
fs.readFile(src, 'utf8', function (error, data) {
if (error) {
// eslint-disable-next-line no-console
console.log(error)
return false
}
fs.writeFile(dst, data.toString(), 'utf8', function (error) {
if (error) {
// eslint-disable-next-line no-console
console.log(error)
PromiseRejectionEvent(error)
return false
}
// console.log('CSS寫入成功')
fs.unlink(src, function () { // css刪除成功
})
})
})
}
// 復(fù)制目錄
glob.sync(`./${outputDir}/css/*.css`).forEach((filepath, name) => {
let fileNameList = filepath.split('.')
let fileName = fileNameList[1].split('/')[3]// 多頁面頁面目錄
let copyName = filepath.split('/')[3]
let changeDirectory = `./${outputDir}/${fileName}/css`// 多頁面JS文件地存放址
if (!fileName.includes('chunk-')) {
/* eslint-disable-next-line */
fs.exists(changeDirectory, function (exists) {
if (exists) {
// console.log(`${fileName}下CSS文件已經(jīng)存在`)
callbackFileCss(filepath, `${changeDirectory}/${copyName}`)
} else {
fs.mkdir(changeDirectory, function () {
callbackFileCss(filepath, `${changeDirectory}/${copyName}`)
// console.log(`${fileName}下CSS文件創(chuàng)建成功`)
})
}
})
}
})
/**
* html文件替換
* @param src
* @param dst
*/
var callbackFile = function (src, dst, name, filepath) {
const index = publicPath.lastIndexOf('/')
let pt = publicPath
if (index !== -1) {
const count = publicPath.length
if (index + 1 === count) {
pt = publicPath.slice(0, index - 1)
}
}
fs.readFile(src, 'utf8', function (error, data) {
if (error) {
// eslint-disable-next-line no-console
console.log(error)
return false
}
let regCss = new RegExp(pt + '/css/' + name + '', 'g')
let regJs = new RegExp(pt + '/js/' + name + '', 'g')
let htmlContent = data.toString().replace(regCss, `./css/${name}`).replace(regJs, `./js/${name}`)
fs.writeFile(dst, htmlContent, 'utf8', function (error) {
if (error) {
// eslint-disable-next-line no-console
console.log(error)
return false
}
// console.log('html重新寫入成功')
if (src.indexOf('/index.html') === -1) {
fs.unlink(src, function () {
// console.log('html刪除成功')
})
}
fs.unlink(filepath, function () { // css刪除成功
})
fs.unlink(filepath + '.map', function () { // css刪除成功
})
})
})
}
// 復(fù)制目錄
glob.sync(`./${outputDir}/js/*.js`).forEach((filepath, name) => {
let fileNameList = filepath.split('.')
let fileName = fileNameList[1].split('/')[3]// 多頁面頁面目錄
let thisDirectory = `./${outputDir}/${fileName}/${fileName}.html`// 多頁面JS文件地存放址
let changeDirectory = `./${outputDir}/${fileName}/index.html`// 多頁面JS文件地存放址
if (!fileName.includes('chunk-')) {
callbackFile(thisDirectory, changeDirectory, fileName, filepath)
}
})
config配置
// vue.config.js
let pageMethod = require('./script/getPages.js')
const pages = pageMethod.pages()
// build-s編譯不能將publicPath設(shè)置為'./'或'',會導(dǎo)致相對路徑資源路徑混亂
module.exports = {
pages,
publicPath: '/',
outputDir: 'dist'
}
package.json
{
...
"scripts": {
"serve": "vue-cli-service serve --open ",
"build-s": "vue-cli-service build --mode ps && node script/splitBuild.js",
"build": "vue-cli-service build",
...
},
...
}
使用說明
-
在src中創(chuàng)建pages文件夾
-
pages中創(chuàng)建的每一個文件夾就是一個單頁面目錄
-
我們在對應(yīng)單頁面目錄里創(chuàng)建對應(yīng)html,vue及js文件即可.
// html 就是頁面的初始html(傳統(tǒng)項目一般在public里面)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>hello-world</title>
</head>
<body>
<noscript>
<strong>We're sorry but hello-world doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
// js文件 項目初始化js
import Vue from 'vue'
import App from './index.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount('#app')
<template>
<div id="app">
<img alt="Vue logo" src="../../assets/logo.png">
<p>頁面2URL:http://localhost:8080/index2/</p>
</div>
</template>
<script>
// vue主頁面
export default {
name: 'app'
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
不足之處,歡迎訪問DLLCN的學(xué)習(xí)筆記進行批評與討論,一起成長,一起學(xué)習(xí).