vue开发多页应用最简单的方式就是使用vue.config.js的pages设置:
// vue.config.js
const path = require('path');
const utils = require('./build/utils.js')
module.exports = {
pages: utils.globPages(),
};
// utils.js
const path = require('path');
const glob = require('glob');
const merge = require("webpack-merge");
const PAGE_PATH = path.resolve(__dirname, '../src/pages');
// pages 多页面配置
exports.globPages = customConfig => {
let entryFiles = glob.sync(PAGE_PATH + '/*/*.js');
let map = {};
entryFiles.forEach(filePath => {
const lastSlashPos = filePath.lastIndexOf('\/');
let filename = filePath.substring(lastSlashPos + 1, filePath.lastIndexOf('.'));
let conf = {
entry: filePath,
template: filePath.replace(/\.js$/, '.html'),
// 在 dist/index.html 的输出
filename: filename + '.html',
// 如果不加这行则每个页面都会引入共享的js脚本
chunks: ['chunk-vendors', 'chunk-common', filename],
inject: true,
};
if (customConfig) {
conf = merge(conf, customConfig);
}
if (process.env.NODE_ENV === 'production') {
conf = merge(conf, {
minify: {
removeComments: true, // 删除 html 中的注释代码
// collapseWhitespace: true, // 删除 html 中的空白符
// removeAttributeQuotes: true // 删除 html 元素中属性的引号
},
chunksSortMode: 'manual'// 按 manual 的顺序引入
});
}
map[filename] = conf;
})
return map;
}
注意chunks引用的包名必须正确,可以检查输出目录【一般是dist】校对,否则达不到共享js代码的目的。
目录结构:
pakage.json
vue.config.js
src
-- pages
-- -- index
-- -- -- App.vue
-- -- -- index.html
-- -- -- index.js
-- -- user
-- -- -- App.vue
-- -- -- user.html
-- -- -- user.js
......