vue-cli3 配置多页面
多个页面时, 目录结构
├── src├── pages├── home| ├── home.html| └── home.js├── about| ├── about.html| └── about.js
vue.config.js 添加
pages: {home : {entry: 'src/pages/home/home.js',template: 'public/home.html',filename: 'home.html'},}
动态配置
pages: getPages(),// 辅助函数var path = require("path");var glob = require("glob");function getPages() {var PAGE_PATH = path.resolve(__dirname, "./src/pages");var entryFiles = glob.sync(PAGE_PATH + "/*/*.js");var map = {};entryFiles.forEach((filePath) => {const filename = filePath.substring(filePath.lastIndexOf("/") + 1,filePath.lastIndexOf("."));map[filename] = {entry: "src/pages/" + filename + "/" + filename + ".js",template: "public/" + filename + ".html",filename: filename + ".html",};});return map;}
vue-cli2配置多页面
借助glob第三方库, 使用shell模式匹配文件。(glob是webpack安装时依赖的一个第三方模块)
cli2中需要在build/webpack.base.conf.js中修改entry
entry: entries()// 辅助函数function entries () {const PAGE_PATH = path.resolve(__dirname, './src/pages')const entryFiles = glob.sync(PAGE_PATH + '/*/*.js')let map = {};entryFiles.forEach(filePath => {const filename = filePath.substring(filePath.lastIndexOf("/") +1,filePath.lastIndexOf("."))map[filename] = filePath;})return map;}
分别在build/webpack.dev.conf.js和build/webpack.prod.conf.js中修改plugins
plugins: [].concat(htmls())// 辅助函数function htmls () {const PAGE_PATH = path.resolve(__dirname, './src/pages')let entryHtml = glob.sync(PAGE_PATH + "/*/*.html");let arr = [];entryHtml.forEach(filePath => {let filename = filePath.substring(filePath.lastIndexOf("/") + 1,filePath.lastIndexOf("."));let conf = {template: filePath, // 模板来源filename: filename + ".html", // 文件名称chunks: ["manifest", "vendor", filename], // 页面模板需要加对应的js脚本,如果不加这行则每个页面都会引入所有的js脚本inject: true};if (process.env.NODE_ENV === "production") {conf = merge(conf, {minify: {removeComments: true,collapseWhitespace: true,removeAttributeQuotes: true},chunksSortMode: "dependency"});}arr.push(new HtmlWebpackPlugin(conf));});return arr;};
webpack配置多页面
webpack项目, entry作为入口, output作为出口, 借助htmlwebpackplugin插件 把静态资源引入到html中。
普通单页面配置:
var HtmlWebpackPlugin = require('html-webpack-plugin');var path = require('path');var webpackConfig = {entry: 'index.js',output: {path: path.resolve(__dirname, './dist'),filename: 'index_bundle.js'},plugins: [new HtmlWebpackPlugin({template: './src/index.html',filename: 'index.html',})]};
配置文件
var webpackConfig = {entry: {home: "./pages/home/home.js",about: "./pages/about/about.js",},output: {path: path.resolve(__dirname, './dist'),filename: '[name].js'},plugins: [new HtmlWebpackPlugin({template: './src/pages/home/home.html',filename: 'home.html',}), new HtmlWebpackPlugin({template: './src/pages/about/about.html',filename: 'about.html',})]};
参考文献:
https://cli.vuejs.org/zh/config/#pages
https://www.webpackjs.com/configuration/
