vue配置多页面的实现方法


Posted in Javascript onMay 22, 2018

1.安装环境

①安装node.js 并添加入环境变量PATH

②安装淘宝NPM镜像

$ npm install -g cnpm --registry=https://registry.npm.taobao.org

③安装webpack

npm install webpack -g

④安装vue-cli脚手架

npm install -g vue-cli

⑤创建项目模板 vue init wepack vue-multipage-demo

⑥cmd进入到要放项目的文件夹

⑦安装 cnpm install

2.目录结构调整

vue配置多页面的实现方法vue配置多页面的实现方法

3.配置文件修改

①添加依赖 glob (返回目录中的所有子文件)

npm install glob

②修改build文件夹中的utils.js文件

//新增代码
var glob = require('glob');
// 页面模板
var HtmlWebpackPlugin = require('html-webpack-plugin');
// 取得相应的页面路径,因为之前的配置,所以是src文件夹下的pages文件夹
var PAGE_PATH = path.resolve(__dirname, '../src/pages');
// 用于做相应的merge处理
var merge = require('webpack-merge');


//多入口配置
// 通过glob模块读取pages文件夹下的所有对应文件夹下的js后缀文件,如果该文件存在
// 那么就作为入口处理

exports.entries = function () {
 var entryFiles = glob.sync(PAGE_PATH + '/*/*.js')
 var map = {}
 entryFiles.forEach((filePath) => {
  var filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'))
  map[filename] = filePath
 })
 return map
}

//多页面输出配置
// 与上面的多页面入口配置相同,读取pages文件夹下的对应的html后缀文件,然后放入数组中
exports.htmlPlugin = function () {
 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',
   // 页面模板需要加对应的js脚本,如果不加这行则每个页面都会引入所有的js脚本
   chunks: ['manifest', 'vendor', filename],
   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.base.conf.js文件

function resolve (dir) {
 return path.join(__dirname, '..', dir)
}

const createLintingRule = () => ({
 test: /\.(js|vue)$/,
 loader: 'eslint-loader',
 enforce: 'pre',
 include: [resolve('src'), resolve('test')],
 options: {
 formatter: require('eslint-friendly-formatter'),
 emitWarning: !config.dev.showEslintErrorsInOverlay
 }
})

module.exports = {
 context: path.resolve(__dirname, '../'),
//注释代码开始
 // entry: {
 // app: './src/main.js'
 // },
//注释代码结束
//新增代码开始
 entry: utils.entries(),
//新增代码结束
 output: {
 path: config.build.assetsRoot,
 filename: '[name].js',
 publicPath: process.env.NODE_ENV === 'production'
  ? config.build.assetsPublicPath
  : config.dev.assetsPublicPath
 },
 resolve: {
 extensions: ['.js', '.vue', '.json'],
 alias: {
  'vue$': 'vue/dist/vue.esm.js',
  '@': resolve('src'),
 }
 },
 module: {
 rules: [
  ...(config.dev.useEslint ? [createLintingRule()] : []),
  {
  test: /\.vue$/,
  loader: 'vue-loader',
  options: vueLoaderConfig
  },
  {
  test: /\.js$/,
  loader: 'babel-loader',
  include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
  },
  {
  test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
  loader: 'url-loader',
  options: {
   limit: 10000,
   name: utils.assetsPath('img/[name].[hash:7].[ext]')
  }
  },
  {
  test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
  loader: 'url-loader',
  options: {
   limit: 10000,
   name: utils.assetsPath('media/[name].[hash:7].[ext]')
  }
  },
  {
  test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
  loader: 'url-loader',
  options: {
   limit: 10000,
   name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
  }
  }
 ]
 },
 node: {
 // prevent webpack from injecting useless setImmediate polyfill because Vue
 // source contains it (although only uses it if it's native).
 setImmediate: false,
 // prevent webpack from injecting mocks to Node native modules
 // that does not make sense for the client
 dgram: 'empty',
 fs: 'empty',
 net: 'empty',
 tls: 'empty',
 child_process: 'empty'
 }
}

④修改webpack.dev.conf.js文件

plugins: [
 new webpack.DefinePlugin({
  'process.env': require('../config/dev.env')
 }),
 new webpack.HotModuleReplacementPlugin(),
 new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
 new webpack.NoEmitOnErrorsPlugin(),
 // https://github.com/ampedandwired/html-webpack-plugin
 //多页面输出配置
 //注释代码开始
  // new HtmlWebpackPlugin({
  // filename: 'index.html',
  // template: 'index.html',
  // inject: true
  // }),
 //注释代码结束
 // copy custom static assets
 new CopyWebpackPlugin([
  {
  from: path.resolve(__dirname, '../static'),
  to: config.dev.assetsSubDirectory,
  ignore: ['.*']
  }
 ])
 //新增代码开始
 ].concat(utils.htmlPlugin())
 //新增代码结束
})

⑤修改webpack.prod.conf.js文件

'use strict'
 const path = require('path')
 const utils = require('./utils')
 const webpack = require('webpack')
 const config = require('../config')
 const merge = require('webpack-merge')
 const baseWebpackConfig = require('./webpack.base.conf')
 const CopyWebpackPlugin = require('copy-webpack-plugin')
 
 const HtmlWebpackPlugin = require('html-webpack-plugin')
 const ExtractTextPlugin = require('extract-text-webpack-plugin')
 const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
 const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
 
 const env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : require('../config/prod.env')
 
 const webpackConfig = merge(baseWebpackConfig, {
  module: {
  rules: utils.styleLoaders({
   sourceMap: config.build.productionSourceMap,
   extract: true,
   usePostCSS: true
  })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  output: {
  path: config.build.assetsRoot,
  filename: utils.assetsPath('js/[name].[chunkhash].js'),
  chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
  // http://vuejs.github.io/vue-loader/en/workflow/production.html
  new webpack.DefinePlugin({
   'process.env': env
  }),
  new UglifyJsPlugin({
   uglifyOptions: {
   compress: {
    warnings: false
   }
   },
   sourceMap: config.build.productionSourceMap,
   parallel: true
  }),
  // extract css into its own file
  new ExtractTextPlugin({
   filename: utils.assetsPath('css/[name].[contenthash].css'),
   // Setting the following option to `false` will not extract CSS from codesplit chunks.
   // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
   // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`, 
   // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
   allChunks: true,
  }),
  // Compress extracted CSS. We are using this plugin so that possible
  // duplicated CSS from different components can be deduped.
  new OptimizeCSSPlugin({
   cssProcessorOptions: config.build.productionSourceMap
   ? { safe: true, map: { inline: false } }
   : { safe: true }
  }),
  // generate dist index.html with correct asset hash for caching.
  // you can customize output by editing /index.html
  // see https://github.com/ampedandwired/html-webpack-plugin
  //注释代码开始
  // new HtmlWebpackPlugin({
  // filename: process.env.NODE_ENV === 'testing'
  //  ? 'index.html'
  //  : config.build.index,
  // template: 'index.html',
  // inject: true,
  // minify: {
  //  removeComments: true,
  //  collapseWhitespace: true,
  //  removeAttributeQuotes: true
  //  // more options:
  //  // https://github.com/kangax/html-minifier#options-quick-reference
  // },
   // necessary to consistently work with multiple chunks via CommonsChunkPlugin
  // chunksSortMode: 'dependency'
  // }),
  //注释代码结束
  // keep module.id stable when vendor modules does not change
  new webpack.HashedModuleIdsPlugin(),
  // enable scope hoisting
  new webpack.optimize.ModuleConcatenationPlugin(),
  // split vendor js into its own file
  new webpack.optimize.CommonsChunkPlugin({
   name: 'vendor',
   minChunks (module) {
   // any required modules inside node_modules are extracted to vendor
   return (
    module.resource &&
    /\.js$/.test(module.resource) &&
    module.resource.indexOf(
    path.join(__dirname, '../node_modules')
    ) === 0
   )
   }
  }),
  // extract webpack runtime and module manifest to its own file in order to
  // prevent vendor hash from being updated whenever app bundle is updated
  new webpack.optimize.CommonsChunkPlugin({
   name: 'manifest',
   minChunks: Infinity
  }),
  // This instance extracts shared chunks from code splitted chunks and bundles them
  // in a separate chunk, similar to the vendor chunk
  // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
  new webpack.optimize.CommonsChunkPlugin({
   name: 'app',
   async: 'vendor-async',
   children: true,
   minChunks: 3
  }),
 
  // copy custom static assets
  new CopyWebpackPlugin([
   {
   from: path.resolve(__dirname, '../static'),
   to: config.build.assetsSubDirectory,
   ignore: ['.*']
   }
  ])
  //修改代码开始 
  ].concat(utils.htmlPlugin())
  //修改代码结束
 })
 
 if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin')
 
  webpackConfig.plugins.push(
  new CompressionWebpackPlugin({
   asset: '[path].gz[query]',
   algorithm: 'gzip',
   test: new RegExp(
   '\\.(' +
   config.build.productionGzipExtensions.join('|') +
   ')$'
   ),
   threshold: 10240,
   minRatio: 0.8
  })
  )
 }
 
 if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
 }
 
 module.exports = webpackConfig

多页面的配置完成 cnpm run dev

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
正则表达式判断是否存在中文和全角字符和判断包含中文字符串长度
Sep 27 Javascript
说说掌握JavaScript语言的思想前提想学习js的朋友可以看看
Apr 01 Javascript
一个可以随意添加多个序列的tag函数
Jul 21 Javascript
javascript中的关于类型转换的性能优化
Dec 14 Javascript
js关闭当前页面(窗口)的几种方式总结
Mar 05 Javascript
js中substring和substr的详细介绍与用法
Aug 29 Javascript
JS实现状态栏跑马灯文字效果代码
Oct 24 Javascript
javascript 缓冲运动框架的实现
Sep 29 Javascript
微信小程序支付功能 php后台对接完整代码分享
Jun 12 Javascript
关于vue表单提交防双/多击的例子
Oct 31 Javascript
微信小程序swiper左右扩展各显示一半代码实例
Dec 05 Javascript
微信小程序实现上传多张图片、删除图片
Jul 29 Javascript
vue.js使用v-model指令实现的数据双向绑定功能示例
May 22 #Javascript
详解js类型判断
May 22 #Javascript
vue.js过滤器+ajax实现事件监听及后台php数据交互实例
May 22 #Javascript
swiper 自动图片无限轮播实现代码
May 21 #Javascript
JS动态插入脚本和插入引用外部链接脚本的方法
May 21 #Javascript
通过jquery toggleClass()属性制作文章段落更改背景颜色
May 21 #jQuery
基于Vue的延迟加载插件vue-view-lazy
May 21 #Javascript
You might like
德生PL990的分析评价
2021/03/02 无线电
实现获取http内容的php函数分享
2014/02/16 PHP
jquery 输入框数字限制插件
2009/11/10 Javascript
javascript权威指南 学习笔记之变量作用域分享
2011/09/28 Javascript
Javascript中的isNaN函数使用说明
2011/11/10 Javascript
javascript中的undefined和not defined区别示例介绍
2014/02/26 Javascript
JavaScript设计模式之单例模式实例
2014/09/24 Javascript
JavaScript将当前时间转换成UTC标准时间的方法
2015/04/06 Javascript
js实现超简单的展开、折叠目录代码
2015/08/28 Javascript
NodeJS的Promise的用法解析
2016/05/05 NodeJs
javascript匀速动画和缓冲动画详解
2016/10/20 Javascript
jQuery实现隔行变色的方法分析(对比原生JS)
2016/11/18 Javascript
vue2.0 keep-alive最佳实践
2017/07/06 Javascript
angular或者js怎么确定选中ul中的哪几个li
2017/08/16 Javascript
微信小程序实现下载进度条的方法
2017/12/08 Javascript
微信小程序实现收藏与取消收藏切换图片功能
2018/08/03 Javascript
JS隐藏号码中间4位代码实例
2019/04/09 Javascript
JavaScript自动生成 年月范围 选择功能完整示例【基于jQuery插件】
2019/09/03 jQuery
vuex(vue状态管理)的特殊应用案例分享
2020/03/03 Javascript
python 实现文件的递归拷贝实现代码
2012/08/02 Python
Python2.x利用commands模块执行Linux shell命令
2016/03/11 Python
完美解决python遍历删除字典里值为空的元素报错问题
2016/09/11 Python
python按比例随机切分数据的实现
2019/07/11 Python
python matplotlib库绘制散点图例题解析
2019/08/10 Python
python程序中的线程操作 concurrent模块使用详解
2019/09/23 Python
html5触摸事件判断滑动方向的实现
2018/06/05 HTML / CSS
金属材料工程个人求职的自我评价
2013/12/04 职场文书
大学班长的职责
2014/01/27 职场文书
学校感恩教育活动总结
2014/07/07 职场文书
小学生纪念九一八事变演讲稿
2014/09/14 职场文书
大专毕业生自我鉴定范文(2篇)
2014/09/27 职场文书
毕业实习指导教师评语
2014/12/31 职场文书
go语言中http超时引发的事故解决
2021/06/02 Golang
springboot+WebMagic+MyBatis爬虫框架的使用
2021/08/07 Java/Android
jdbc中自带MySQL 连接池实践示例
2022/07/23 MySQL
Li list-style-image 图片垂直居中实现方法
2023/05/21 HTML / CSS