1. 程式人生 > >vue搭建多頁面開發環境

vue搭建多頁面開發環境

url build node too def clas and 分割線 warning

自從習慣開發了單頁面應用,對多頁面的頁面間的相互跳轉間沒有過渡效果、難維護極度反感。但是最近公司技術老大說,當一個應用越來越大的時候單頁面模式應付不來,但是沒講怎麽應付不來,所以還得自己去復習一遍這兩者的區別:

技術分享圖片

這樣對比的話,單頁面的優勢確實很大,但當我自己去打開某寶,某東的移動端頁面時,確實它們都是多頁面應用。為什麽?我能想到的就幾點:

1.單頁面使用的技術對低版本的瀏覽器不友好,大公司還得兼顧使用低版本瀏覽器的用戶啊

2.功能模塊開發來說,比如說單頁面的業務公用組件,有時候你都不知道分給誰開發

3.seo優化吧(PS:既然是大應用應該很多人都知道,為什麽還要做搜索引擎優化)

--------------------------------------------------華麗分割線------------------------------------------------------------------------------------

公司開發移動端使用的技術是vue,其實老大在要求使用多頁面開發的時候,已經搭了一個vue多頁面的腳手架供給我們去使用,但是我去看了看源碼的時候寫得很一般,所以決定自己重新去寫過。

思路:

由於vue-cli已經寫好了單頁面的webpack文件,不去改動之前是它默認的一個頁面引用打包的資源。既然是多頁面,那麽把webpack入口文件改成多個就好了啊。未改動時的webpack.base.conf.js(這個JS的功能主要在於全局配置,比如入口文件,出口文件,解析規則等)

技術分享圖片

1 // 把箭頭部分的入口文件改為以下
2 entry: {
3   ‘index‘: ‘..../main.js‘  // 註意省略號是實際開發時的項目路徑
4   ‘product‘: ‘..../main.js‘    
5 }

但是這樣做效率得多低下,每增加一個新頁面就要手動去添加新的入口,所以這裏把入口文件封裝為一個函數:

技術分享圖片
 1 /**
 2  * 獲取多頁面入口文件
 3  * @globPath 文件路徑
 4  */
 5 const glob = require(‘glob‘)
 6 function getEntries(globPath)  {
 7   const entries = glob.sync(globPath).reduce((result, entry) => {
 8     const moduleName = path.basename(path.dirname(entry)) // 獲取模塊名稱
 9     result[moduleName] = entry
10     return result
11   }, {})
12   return entries
13 }
技術分享圖片

註意在使用nodejs的glob模塊之前,記得先下載依賴

測試一下這個函數

技術分享圖片

然後把webpack.base.config.js改為如下:

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

註意我的多頁面目錄:

技術分享圖片

---------------------------------------華麗分割線----------------------------------------------------------------------

公共配置搞完之後是打包文件:webpack.prod.conf.js,打包文件的修改主要是輸出文件的配置,因為要對應入口文件的文件夾,還有就是一個頁面對應一個htmlwebpackplugin配置,這個配置是加在文件的plugins裏面的,按照上面的消除手動加入配置的思路這裏也加入htmlwebpackplugin的配置函數

技術分享圖片
/**
 * 頁面打包
 * @entries 打包文件
 * @config 參數配置
 * @module 使用的主體
 */
const HtmlWebpackPlugin = require(‘html-webpack-plugin‘)
function pack (entries, module) {
  for (const path in entries) {
    const conf = {
      filename: `modules/${path}/index.html`,
      template: entries[path],   // 模板路徑
      inject: true,
      chunks: [‘manifest‘, ‘vendor‘, path]   // 必須先引入公共依賴
    }
    module.plugins.push(new HtmlWebpackPlugin(conf))
  }
}
技術分享圖片

最終打包文件改為如下

技術分享圖片
‘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 = require(‘../config/prod.env‘)


const glob = require(‘glob‘)
function getEntries (globPath){
  const entries = glob.sync(globPath).reduce((result, entry) => {
    const moduleName = path.basename(path.dirname(entry)) // 獲取模塊名稱
    result[moduleName] = entry
    return result
  }, {})
  return entries
}

const entries = getEntries(‘./src/modules/**/*.html‘)   // 獲取多頁面所有入口文件

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: ‘modules/[name]/[name].[chunkhash].js‘,
    // publicPath: ‘/‘ // 改為相對路徑
    // 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
    // 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: [‘.*‘]
      }
    ])
  ]
})

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())
}


function pack (entries, module) {
  for (const path in entries) {
    const conf = {
      filename: `modules/${path}/index.html`,
      template: entries[path],   // 模板路徑
      inject: true,
      chunks: [‘manifest‘, ‘vendor‘, path]   // 必須先引入公共依賴
    }
    module.plugins.push(new HtmlWebpackPlugin(conf))
  }
}

pack(entries, webpackConfig)
module.exports = webpackConfig
技術分享圖片

然後啟動npm run build嘗試打包文件

技術分享圖片

OK,多頁面的打包完成

參考:http://blog.csdn.net/u013291076/article/details/53667382

vue搭建多頁面開發環境