一、使用vue-cli创建项目
$ vue init webpack project
片刻之后,project项目创建完成。
$ cd project & npm run dev
然后打开浏览器,访问https://localhost:8080 ,正常情况下能看到一个Vue项目的页面。
至此,我们就使用vue-cli创建了一个项目
二、将这个项目修改成多页应用
1.先安装一个npm包
$ npm i glob -D
2.打开build/utils.js
先引入glob、webpack-merge、html-webpack-plugin包
再定义PAGE_PATH
const glob = require('glob') const merge = require('webpack-merge') const htmlWebpackPlugin = require('html-webpack-plugin') const PAGE_PATH = path.resolve(__dirname, '../src/pages')
然后新建并暴露生成entry入口配置的方法
// 生成entry入口配置 exports.getEntries = function () { let entryFiles = glob.sync(PAGE_PATH + '/*/*.js') let entries = {} entryFiles.forEach(filePath => { let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.')) entries[filename] = filePath }) return entries }
再新建并暴露生成plugin配置的方法
// 生成plugin配置 exports.getHtmlPlugins = function () { let entryFiles = glob.sync(PAGE_PATH + '/*/*.html') let htmlPlugins = [] entryFiles.forEach(filePath => { let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.')) let conf = { filename: filename + '.html', template: filePath, chunks: ['manifest', 'vendor', filename], inject: true } if (process.env.NODE_ENV === 'production') { conf = merge(conf, { minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunksSortMode: 'dependency' }) } htmlPlugins.push(new htmlWebpackPlugin(conf)) }) return htmlPlugins }
3.打开build/webpack.base.config.js
修改entry配置项
entry: utils.getEntries(),
4.打开build/webpack.dev.config.js
修改plugin配置项
将之前plugin里面的new htmlWebpackPlugin()删除,将utils里面定义的htmlWebplackPlugin添加进来
plugin: [ // 其他plugin ...utils.getHtmlPlugins() ]
5.打开build/webpack.prod.config.js
修改plugin配置项
将之前plugin里面的new htmlWebpackPlugin()删除,将utils里面定义的htmlWebplackPlugin添加进来
plugin: [ // 其他plugin ...utils.getHtmlPlugins() ]
至此,webpack配置修改完毕
三、修改项目结构
1.在src目录下新建pages文件夹,在pages文件夹下新建hello文件夹
2.将src目录下除pages文件夹外的所有文件夹和文件都移到hello文件夹下,并将main.js重命名为hello.js
3.将根目录下的index.html移到hello文件夹下,并将index.html重命名为hello.html
4.重新运行npm run dev
$ npm run dev
片刻之后,打开https://localhost:8080/hello.html
正常情况下,可以看到和之前一样的页面
至此,vue-cli创建的项目改成多页应用完毕
关于修改后的脚手架的两点说明
1.src/pages下面的每个文件夹名称尽量和这个文件夹下面的入口js文件、html文件保持相同
2.打包之后src/pages下面的每个文件夹都会生成一个对应的html页面,这个页面可以使用自己的vur-router路由,也可以使用自己的vuex
关于修改后的脚手架的一点吐槽
src/pages下面每新建一个页面,就要写一个相似度99%的html文件(可能只有title不同),所以就觉得有些费劲。
后来又通过修改webpack配置,使用一个单独的js文件来管理页面名称和title,这样做的优点是不用每次新建一个页面都要写一个相似度99%的html文件,但是带来的问题是需要手动维护这个js文件,所以并没有优化多少。