search
HomeWeb Front-endJS TutorialHow to configure multiple pages using vue

这次给大家带来如何使用vue配置多页面,使用vue配置多页面的注意事项有哪些,下面就是实战案例,一起来看一下。

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.目录结构调整

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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

如何进行Angular网络请求封装

如何实现vue input输入框模糊查询

The above is the detailed content of How to configure multiple pages using vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何在Word中复制页面如何在Word中复制页面Feb 20, 2024 am 10:09 AM

是否要复制MicrosoftWord中的页面,并保持格式不变?这是一个聪明的想法,因为当您想要创建特定文档布局或格式的多个副本时,在Word中复制页面可能是一种有用的节省时间的技术。本指南将逐步引导您在Word中复制页面的过程,无论是创建模板还是复制文档中的特定页面。这些简单的说明旨在帮助您轻松地重新制作页面,省去从头开始的麻烦。为什么要在MicrosoftWord中复制页面?在Word中复制页面非常有益的原因有以下几点:当您有一个具有特定布局或格式的文档要复制时。与从头开始重新创建整个页面不同

处理Laravel页面无法正确显示CSS的方法处理Laravel页面无法正确显示CSS的方法Mar 10, 2024 am 11:33 AM

《处理Laravel页面无法正确显示CSS的方法,需要具体代码示例》在使用Laravel框架开发Web应用时,有时候会遇到页面无法正确显示CSS样式的问题,这可能会导致页面呈现不正常的样式,影响用户体验。本文将介绍一些处理Laravel页面无法正确显示CSS的方法,并提供具体的代码示例,帮助开发者解决这一常见问题。一、检查文件路径首先要检查CSS文件的路径是

3秒跳转页面实现方法:PHP编程指南3秒跳转页面实现方法:PHP编程指南Mar 25, 2024 am 10:42 AM

标题:3秒跳转页面实现方法:PHP编程指南在网页开发中,页面跳转是常见的操作,一般情况下我们使用HTML中的meta标签或者JavaScript的方法进行页面跳转。不过,在某些特定的情况下,我们需要在服务器端进行页面跳转。本文将介绍如何使用PHP编程实现一个在3秒内自动跳转到指定页面的功能,同时会给出具体的代码示例。PHP实现页面跳转的基本原理PHP是一种在

如何在iPhone上自定义和编辑待机模式:iOS 17的新功能如何在iPhone上自定义和编辑待机模式:iOS 17的新功能Sep 21, 2023 pm 04:01 PM

待机是iOS17更新中的一项新功能,它提供了一种新的增强方式,可以在手机快速闲置时访问信息。通过StandBy,您可以方便地查看时间、查看即将发生的事件、浏览日历、获取您所在位置的天气更新等等。激活后,iPhone在充电时设置为横向时会直观地进入待机模式。此功能非常适合床头柜等无线充电点,或者在日常任务中离开iPhone充电时。它允许您轻扫待机中显示的各种小部件,以访问来自各种应用程序的不同信息集。但是,您可能希望根据您的偏好和您经常需要的信息修改这些小部件,甚至删除一些小部件。因此,让我们深入

重新排列、禁用和删除 iPhone 主屏幕页面的方法重新排列、禁用和删除 iPhone 主屏幕页面的方法Nov 29, 2023 am 08:22 AM

在iOS中,Apple允许您禁用iPhone上的单个主屏幕页面。还可以重新排列主屏幕页面的顺序,并直接删除页面,而不仅仅是禁用它们。这是它的工作原理。如何重新排列主屏幕页面触摸并按住主屏幕上的空格可进入抖动模式。轻点代表主屏幕页面的圆点行。在显示的主屏幕网格中,轻触并拖动页面以将其相对于其他页面重新排列。其他人会移动以响应您的拖拽动作。当您对新排列感到满意时,点击屏幕右上角的“完成”,然后再次点击“完成”以退出抖动模式。如何禁用或删除主屏幕页面触摸并按住主屏幕上的空格可进入抖动模式。轻点代表主屏

如何在Nginx配置Cookie安全策略如何在Nginx配置Cookie安全策略Jun 10, 2023 pm 12:54 PM

随着互联网的不断发展和普及,Web应用程序已成为人们日常生活中必不可少的一部分,这也决定了Web应用程序的安全问题非常重要。在Web应用程序中,Cookie被广泛使用来实现用户身份认证等功能,然而Cookie也存在着安全风险,因此在配置Nginx时,必须设定适当的Cookie安全策略,以保证Cookie的安全性。下面是一些在Nginx中配置Cookie安全策

如何快速刷新网页?如何快速刷新网页?Feb 18, 2024 pm 01:14 PM

页面刷新在我们日常的网络使用中非常常见,当我们访问一个网页后,有时候会遇到一些问题,比如网页加载不出来或者显示不正常等。这时候我们通常会选择刷新页面来解决问题,那么如何快速地刷新页面呢?下面我们就来探讨一下页面刷新的快捷键。页面刷新快捷键是一种通过键盘操作来快速刷新当前网页的方法。在不同的操作系统和浏览器中,页面刷新的快捷键可能有所不同。下面我们以常见的W

MySQL连接池的最大连接数如何设置?MySQL连接池的最大连接数如何设置?Jun 30, 2023 pm 12:55 PM

如何配置MySQL连接池的最大连接数?MySQL是一个开源的关系型数据库管理系统,被广泛应用于各种领域的数据存储与管理。在使用MySQL时,我们常常需要使用连接池来管理数据库连接,以提高性能和资源利用率。连接池是一种维护和管理数据库连接的技术,它能够在需要时提供数据库连接,并在不需要时回收连接,从而减少了连接的重复创建和销毁。而连接池的最大连接数则是连接池所

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!