基于vue-cli的改造的多页面开发脚手架

项目的GitHub地址:https://github.com/hellobajie/vue-cli-multipage

该脚手架同时支持vux,scss,less

目录结构

vue-cli-multipage
  |---build
  |---config
  |---src
    |---assets  图片
    |---comm  公共的css及js
    |---components  组件
      |---vux.vue vux的dome页面
      |---App.vue
    |---pages  html模板文件
      |---abc.html
      |---main.html
    |---abc.js  根据该js进行页面的打包及调试
    |---main.js 

修改配置文件

构建多页面应用的关键在于向配置对象的plugins子项添加多个HtmlWebpackPlugin。

怎样根据页面的多少动态的添加多个HtmlWebpackPlugin呢,我们需要使用glob插件;

npm install --save-dev glob  安装glob插件

通过glob插件会将特定目录下的文件名存储为一个数组,遍历该数据,生成多个HtmlWebpackPlugin,并插入plugins中;

//webpack.prod.conf.js
var
fileList = glob.sync('./src/*.js'); var fileNameList = []; fileList.forEach(function (item, index) { var name = item.match(/(/)(w+)(.)/g)[0].substring(1, item.match(/(/)(w+)(.)/g)[0].length - 1); fileNameList.push(name); }) var obj = {}; fileList.forEach(function (item, index) { var filename = fileNameList[index]; configObj.entry[filename] = item; configObj.plugins.push(new HtmlWebpackPlugin({ template: './src/pages/' +filename + '.html', filename: filename + '.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunksSortMode: 'dependency', chunks: ['manifest', 'vendor', filename] })) })
//webpack.dev.conf.js
var
fileList = glob.sync('./src/*.js'); var fileNameList = []; fileList.forEach(function (item, index) { var name = item.match(/(/)(w+)(.)/g)[0].substring(1, item.match(/(/)(w+)(.)/g)[0].length - 1); fileNameList.push(name); }) var obj = {}; fileList.forEach(function (item, index) { var filename = fileNameList[index]; configObj.entry[filename] = item; configObj.plugins.push(new HtmlWebpackPlugin({ template: './src/pages/' + filename + '.html', filename: filename + '.html', inject: true, chunks: [filename] })) })

vue-cli问题优化

  1.遇到问题:项目打包后,无法直接在本地直接打开。

    解决办法:在./config/index.js文件中,build下找到assetsPublicPath,将其值改为'./',即打包后,会在相对目录下查找对应的资源;

  2.遇到问题:直接打开打包后的文件,报错webpackJsonp is not defined。

     解决办法:在webpack.prod.conf.js文件中,每个遍历生成的HtmlWebpackPlugin,配置选项中,chunks对应的数组添加'manifest','vendor'。添加这两项的目的是将公用的资源进行单独打包,浏览器缓存后,后面打开的页面就可以直接从缓存中读取。

  3.遇到问题:多次打包后,未被覆盖的文件会被保留下来。

     解决办法:安装clean-webpack-plugin插件,在webpack.prod.conf.js文件的plugins中添加如下代码

new CleanWebpackPlugin(['dist'], {
    root: path.resolve(__dirname, '../'),
}),