当前位置:Gxlcms > JavaScript > vue配置多页面的实现方法

vue配置多页面的实现方法

时间:2021-07-01 10:21:17 帮助过:4人阅读

1.安装环境

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

②安装淘宝NPM镜像

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

③安装webpack

  1. npm install webpack -g

④安装vue-cli脚手架

  1. npm install -g vue-cli

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

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

⑦安装 cnpm install

2.目录结构调整

3.配置文件修改

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

  1. npm install glob

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

  1. //新增代码
  2. var glob = require('glob');
  3. // 页面模板
  4. var HtmlWebpackPlugin = require('html-webpack-plugin');
  5. // 取得相应的页面路径,因为之前的配置,所以是src文件夹下的pages文件夹
  6. var PAGE_PATH = path.resolve(__dirname, '../src/pages');
  7. // 用于做相应的merge处理
  8. var merge = require('webpack-merge');
  9. //多入口配置
  10. // 通过glob模块读取pages文件夹下的所有对应文件夹下的js后缀文件,如果该文件存在
  11. // 那么就作为入口处理
  12. exports.entries = function () {
  13. var entryFiles = glob.sync(PAGE_PATH + '/*/*.js')
  14. var map = {}
  15. entryFiles.forEach((filePath) => {
  16. var filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'))
  17. map[filename] = filePath
  18. })
  19. return map
  20. }
  21. //多页面
输出配置 // 与上面的多页面入口配置相同,读取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文件

  1. function resolve (dir) {
  2. return path.join(__dirname, '..', dir)
  3. }
  4. const createLintingRule = () => ({
  5. test: /\.(js|vue)$/,
  6. loader: 'eslint-loader',
  7. enforce: 'pre',
  8. include: [resolve('src'), resolve('test')],
  9. options: {
  10. formatter: require('eslint-friendly-formatter'),
  11. emitWarning: !config.dev.showEslintErrorsInOverlay
  12. }
  13. })
  14. module.exports = {
  15. context: path.resolve(__dirname, '../'),
  16. //注释代码开始
  17. // entry: {
  18. // app: './src/main.js'
  19. // },
  20. //注释代码结束
  21. //新增代码开始
  22. entry: utils.entries(),
  23. //新增代码结束
  24. output: {
  25. path: config.build.assetsRoot,
  26. filename: '[name].js',
  27. publicPath: process.env.NODE_ENV === 'production'
  28. ? config.build.assetsPublicPath
  29. : config.dev.assetsPublicPath
  30. },
  31. resolve: {
  32. extensions: ['.js', '.vue', '.json'],
  33. alias: {
  34. 'vue$': 'vue/dist/vue.esm.js',
  35. '@': resolve('src'),
  36. }
  37. },
  38. module: {
  39. rules: [
  40. ...(config.dev.useEslint ? [createLintingRule()] : []),
  41. {
  42. test: /\.vue$/,
  43. loader: 'vue-loader',
  44. options: vueLoaderConfig
  45. },
  46. {
  47. test: /\.js$/,
  48. loader: 'babel-loader',
  49. include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
  50. },
  51. {
  52. test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
  53. loader: 'url-loader',
  54. options: {
  55. limit: 10000,
  56. name: utils.assetsPath('img/[name].[hash:7].[ext]')
  57. }
  58. },
  59. {
  60. test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
  61. loader: 'url-loader',
  62. options: {
  63. limit: 10000,
  64. name: utils.assetsPath('media/[name].[hash:7].[ext]')
  65. }
  66. },
  67. {
  68. test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
  69. loader: 'url-loader',
  70. options: {
  71. limit: 10000,
  72. name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
  73. }
  74. }
  75. ]
  76. },
  77. node: {
  78. // prevent webpack from injecting useless setImmediate polyfill because Vue
  79. // source contains it (although only uses it if it's native).
  80. setImmediate: false,
  81. // prevent webpack from injecting mocks to Node native modules
  82. // that does not make sense for the client
  83. dgram: 'empty',
  84. fs: 'empty',
  85. net: 'empty',
  86. tls: 'empty',
  87. child_process: 'empty'
  88. }
  89. }

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

  1. plugins: [
  2. new webpack.DefinePlugin({
  3. 'process.env': require('../config/dev.env')
  4. }),
  5. new webpack.HotModuleReplacementPlugin(),
  6. new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
  7. new webpack.NoEmitOnErrorsPlugin(),
  8. // https://github.com/ampedandwired/html-webpack-plugin
  9. //多页面
输出配置 //注释代码开始 // 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文件

  1. 'use strict'
  2. const path = require('path')
  3. const utils = require('./utils')
  4. const webpack = require('webpack')
  5. const config = require('../config')
  6. const merge = require('webpack-merge')
  7. const baseWebpackConfig = require('./webpack.base.conf')
  8. const CopyWebpackPlugin = require('copy-webpack-plugin')
  9. const HtmlWebpackPlugin = require('html-webpack-plugin')
  10. const ExtractTextPlugin = require('extract-text-webpack-plugin')
  11. const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
  12. const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
  13. const env = process.env.NODE_ENV === 'testing'
  14. ? require('../config/test.env')
  15. : require('../config/prod.env')
  16. const webpackConfig = merge(baseWebpackConfig, {
  17. module: {
  18. rules: utils.styleLoaders({
  19. sourceMap: config.build.productionSourceMap,
  20. extract: true,
  21. usePostCSS: true
  22. })
  23. },
  24. devtool: config.build.productionSourceMap ? config.build.devtool : false,
  25. output: {
  26. path: config.build.assetsRoot,
  27. filename: utils.assetsPath('js/[name].[chunkhash].js'),
  28. chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  29. },
  30. plugins: [
  31. // http://vuejs.github.io/vue-loader/en/workflow/production.html
  32. new webpack.DefinePlugin({
  33. 'process.env': env
  34. }),
  35. new UglifyJsPlugin({
  36. uglifyOptions: {
  37. compress: {
  38. warnings: false
  39. }
  40. },
  41. sourceMap: config.build.productionSourceMap,
  42. parallel: true
  43. }),
  44. // extract css into its own file
  45. new ExtractTextPlugin({
  46. filename: utils.assetsPath('css/[name].[contenthash].css'),
  47. // Setting the following option to `false` will not extract CSS from codesplit chunks.
  48. // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
  49. // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
  50. // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
  51. allChunks: true,
  52. }),
  53. // Compress extracted CSS. We are using this plugin so that possible
  54. // duplicated CSS from different components can be deduped.
  55. new OptimizeCSSPlugin({
  56. cssProcessorOptions: config.build.productionSourceMap
  57. ? { safe: true, map: { inline: false } }
  58. : { safe: true }
  59. }),
  60. // generate dist index.html with correct asset hash for caching.
  61. // you can customize output by editing /index.html
  62. // see https://github.com/ampedandwired/html-webpack-plugin
  63. //注释代码开始
  64. // new HtmlWebpackPlugin({
  65. // filename: process.env.NODE_ENV === 'testing'
  66. // ? 'index.html'
  67. // : config.build.index,
  68. // template: 'index.html',
  69. // inject: true,
  70. // minify: {
  71. // removeComments: true,
  72. // collapseWhitespace: true,
  73. // removeAttributeQuotes: true
  74. // // more options:
  75. // // https://github.com/kangax/html-minifier#options-quick-reference
  76. // },
  77. // necessary to consistently work with multiple chunks via CommonsChunkPlugin
  78. // chunksSortMode: 'dependency'
  79. // }),
  80. //注释代码结束
  81. // keep module.id stable when vendor modules does not change
  82. new webpack.HashedModuleIdsPlugin(),
  83. // enable scope hoisting
  84. new webpack.optimize.ModuleConcatenationPlugin(),
  85. // split vendor js into its own file
  86. new webpack.optimize.CommonsChunkPlugin({
  87. name: 'vendor',
  88. minChunks (module) {
  89. // any required modules inside node_modules are extracted to vendor
  90. return (
  91. module.resource &&
  92. /\.js$/.test(module.resource) &&
  93. module.resource.indexOf(
  94. path.join(__dirname, '../node_modules')
  95. ) === 0
  96. )
  97. }
  98. }),
  99. // extract webpack runtime and module manifest to its own file in order to
  100. // prevent vendor hash from being updated whenever app bundle is updated
  101. new webpack.optimize.CommonsChunkPlugin({
  102. name: 'manifest',
  103. minChunks: Infinity
  104. }),
  105. // This instance extracts shared chunks from code splitted chunks and bundles them
  106. // in a separate chunk, similar to the vendor chunk
  107. // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
  108. new webpack.optimize.CommonsChunkPlugin({
  109. name: 'app',
  110. async: 'vendor-async',
  111. children: true,
  112. minChunks: 3
  113. }),
  114. // copy custom static assets
  115. new CopyWebpackPlugin([
  116. {
  117. from: path.resolve(__dirname, '../static'),
  118. to: config.build.assetsSubDirectory,
  119. ignore: ['.*']
  120. }
  121. ])
  122. //修改代码开始
  123. ].concat(utils.htmlPlugin())
  124. //修改代码结束
  125. })
  126. if (config.build.productionGzip) {
  127. const CompressionWebpackPlugin = require('compression-webpack-plugin')
  128. webpackConfig.plugins.push(
  129. new CompressionWebpackPlugin({
  130. asset: '[path].gz[query]',
  131. algorithm: 'gzip',
  132. test: new RegExp(
  133. '\\.(' +
  134. config.build.productionGzipExtensions.join('|') +
  135. ')$'
  136. ),
  137. threshold: 10240,
  138. minRatio: 0.8
  139. })
  140. )
  141. }
  142. if (config.build.bundleAnalyzerReport) {
  143. const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  144. webpackConfig.plugins.push(new BundleAnalyzerPlugin())
  145. }
  146. module.exports = webpackConfig

多页面的配置完成 cnpm run dev

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

人气教程排行