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 相关文章推荐
jquery插件lazyload.js延迟加载图片的使用方法
Feb 19 Javascript
自己封装的javascript事件队列函数版
Jun 12 Javascript
JQuery实现鼠标移动图片显示描述层的方法
Jun 25 Javascript
浅谈Javascript中Object与Function对象
Sep 26 Javascript
AngularJS数据源的多种获取方式汇总
Feb 02 Javascript
vue2笔记 — vue-router路由懒加载的实现
Mar 03 Javascript
Angular 4依赖注入学习教程之ClassProvider的使用(三)
Jun 04 Javascript
深入解析Vue 组件命名那些事
Jul 18 Javascript
vue axios同步请求解决方案
Sep 29 Javascript
通过cordova将vue项目打包为webapp的方法
Feb 02 Javascript
Layui数据表格跳转到指定页的实现方法
Sep 05 Javascript
javascript使用canvas实现饼状图效果
Sep 08 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
php递归实现无限分类生成下拉列表的函数
2010/08/08 PHP
array_multisort实现PHP多维数组排序示例讲解
2011/01/04 PHP
php设计模式 Interpreter(解释器模式)
2011/06/26 PHP
php实现将任意进制数转换成10进制的方法
2015/04/17 PHP
非常重要的php正则表达式详解
2016/01/04 PHP
javascript 放大镜效果js组件 qsoft.PopBigImage.v0.35 加入了chrome支持
2009/04/07 Javascript
关于window.pageYOffset和document.documentElement.scrollTop
2011/04/05 Javascript
分享20多个很棒的jQuery 文件上传插件或教程
2011/09/04 Javascript
使用javaScript动态加载Js文件和Css文件
2015/10/24 Javascript
jquery实现二级导航下拉菜单效果
2015/12/18 Javascript
Bootstrap入门书籍之(四)菜单、按钮及导航
2016/02/17 Javascript
jQuery使用中可能被XSS攻击的一些危险环节提醒
2016/05/24 Javascript
根据Bootstrap Paginator改写的js分页插件
2016/12/25 Javascript
jQuery常用选择器详解
2017/07/17 jQuery
es6在react中的应用代码解析
2017/11/08 Javascript
快速搭建vue2.0+boostrap项目的方法
2018/04/09 Javascript
解决bootstrap中下拉菜单点击后不关闭的问题
2018/08/10 Javascript
在vue中多次调用同一个定义全局变量的实例
2018/09/25 Javascript
vue 中基于html5 drag drap的拖放效果案例分析
2018/11/01 Javascript
详解vue的数据劫持以及操作数组的坑
2019/04/18 Javascript
优雅的处理vue项目异常实战记录
2019/06/05 Javascript
JavaScript实现电灯开关小案例
2020/03/30 Javascript
浅谈JavaScript中的“!!”作用
2020/08/03 Javascript
Vue使用Ref跨层级获取组件的步骤
2021/01/25 Vue.js
详解如何使用Python编写vim插件
2017/11/28 Python
Python实现的朴素贝叶斯分类器示例
2018/01/06 Python
jupyter notebook 中输出pyecharts图实例
2020/04/23 Python
PyQt5根据控件Id获取控件对象的方法
2019/06/25 Python
python3操作注册表的方法(Url protocol)
2020/02/05 Python
伦敦高达60%折扣的钻石珠宝商:Purely Diamonds
2018/06/24 全球购物
乌克兰在线商店的价格比较:Price.ua
2019/07/26 全球购物
一道Delphi面试题
2016/10/28 面试题
大学生年度自我鉴定
2013/10/31 职场文书
2015年妇女工作总结
2015/05/14 职场文书
如何在CocosCreator里画个炫酷的雷达图
2021/04/16 Javascript
MySQL数据库如何使用Shell进行连接
2022/04/12 MySQL