- 最近一直在忙着做項目 本來想養成一個經常跟新博客的習慣 , 但是實在是太難了 , 每天加班到10點多 。8點能下班都是最好的了 , 小公司真不好待呀
- 分享一下最近半年的vue心得吧
- 我的項目是在他的基礎上改的
PanJiaChen/vueAdmin-template
vuex 咋web上我覺得是雞肋 , 用戶刷新頁面直接就沒了。。。。。。。。。。。

這是我的目錄 , 現在我遇到一個瓶頸 , 就是如何優化 build 的速度問題 , 這個問題隨着頁面原來越多已經發展到越來越恐怖的地方了現在打包一個項目起碼的20分鍾 , 我項目總共有323個頁面

動態路由 322個頁面 , 不算自己寫的組件什么的
先說一下vue webpack 的配置的問題
"scripts": { "dev": "node build/dev-server.js", "build": "node build/build.js", "lint": "eslint --ext .js,.vue src" }
我們 npm run dev 便是運行的 第一條命令 , 類推
build/dev-server.js
require('./check-versions')() // 檢查 Node 和 npm 版本 var config = require('../config') // 獲取 config/index.js 的默認配置 /* ** 如果 Node 的環境無法判斷當前是 dev / product 環境 ** 使用 config.dev.env.NODE_ENV 作為當前的環境 */ if (!process.env.NODE_ENV) process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) var path = require('path') // 使用 NodeJS 自帶的文件路徑工具 var express = require('express') // 使用 express var webpack = require('webpack') // 使用 webpack var opn = require('opn') // 一個可以強制打開瀏覽器並跳轉到指定 url 的插件 var proxyMiddleware = require('http-proxy-middleware') // 使用 proxyTable var webpackConfig = require('./webpack.dev.conf') // 使用 dev 環境的 webpack 配置 // default port where dev server listens for incoming traffic /* 如果沒有指定運行端口,使用 config.dev.port 作為運行端口 */ var port = process.env.PORT || config.dev.port // Define HTTP proxies to your custom API backend // https://github.com/chimurai/http-proxy-middleware /* 使用 config.dev.proxyTable 的配置作為 proxyTable 的代理配置 */ var proxyTable = config.dev.proxyTable /* 使用 express 啟動一個服務 */ var app = express() var compiler = webpack(webpackConfig) // 啟動 webpack 進行編譯 /* 啟動 webpack-dev-middleware,將 編譯后的文件暫存到內存中 */ var devMiddleware = require('webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, stats: { colors: true, chunks: false } }) /* 啟動 webpack-hot-middleware,也就是我們常說的 Hot-reload */ var hotMiddleware = require('webpack-hot-middleware')(compiler) // force page reload when html-webpack-plugin template changes compiler.plugin('compilation', function (compilation) { compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { hotMiddleware.publish({ action: 'reload' }) cb() }) }) // proxy api requests // 將 proxyTable 中的請求配置掛在到啟動的 express 服務上 Object.keys(proxyTable).forEach(function (context) { var options = proxyTable[context] if (typeof options === 'string') { options = { target: options } } app.use(proxyMiddleware(context, options)) }) // handle fallback for HTML5 history API // 使用 connect-history-api-fallback 匹配資源,如果不匹配就可以重定向到指定地址 app.use(require('connect-history-api-fallback')()) // serve webpack bundle output // 將暫存到內存中的 webpack 編譯后的文件掛在到 express 服務上 app.use(devMiddleware) // enable hot-reload and state-preserving // compilation error display // 將 Hot-reload 掛在到 express 服務上 app.use(hotMiddleware) // serve pure static assets // 拼接 static 文件夾的靜態資源路徑 var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) // 為靜態資源提供響應服務 app.use(staticPath, express.static('./static')) // 讓我們這個 express 服務監聽 port 的請求,並且將此服務作為 dev-server.js 的接口暴露 module.exports = app.listen(port, function (err) { if (err) { console.log(err) return } var uri = 'http://localhost:' + port console.log('Listening at ' + uri + '\n') // when env is testing, don't need open it // 如果不是測試環境,自動打開瀏覽器並跳到我們的開發地址 if (process.env.NODE_ENV !== 'testing') { opn(uri) } })
webpack.dev.conf.js
var config = require('../config') // 同樣的使用了 config/index.js var webpack = require('webpack') // 使用 webpack var merge = require('webpack-merge') // 使用 webpack 配置合並插件 var utils = require('./utils') // 使用一些小工具 var baseWebpackConfig = require('./webpack.base.conf') // 加載 webpack.base.conf /* 使用 html-webpack-plugin 插件,這個插件可以幫我們自動生成 html 並且注入到 .html 文件中 */ var HtmlWebpackPlugin = require('html-webpack-plugin') // add hot-reload related code to entry chunks // 將 Hol-reload 相對路徑添加到 webpack.base.conf 的 對應 entry 前 Object.keys(baseWebpackConfig.entry).forEach(function (name) { baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) }) /* 將我們 webpack.dev.conf.js 的配置和 webpack.base.conf.js 的配置合並 */ module.exports = merge(baseWebpackConfig, { module: { // 使用 styleLoaders loaders: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) }, // eval-source-map is faster for development // 使用 #eval-source-map 模式作為開發工具,此配置可參考 DDFE 往期文章詳細了解 devtool: '#eval-source-map', plugins: [ /* definePlugin 接收字符串插入到代碼當中, 所以你需要的話可以寫上 JS 的字符串 */ new webpack.DefinePlugin({ 'process.env': config.dev.env }), // https://github.com/glenjamin/webpack-hot-middleware#installation--usage new webpack.optimize.OccurenceOrderPlugin(), /* HotModule 插件在頁面進行變更的時候只會重回對應的頁面模塊,不會重繪整個 html 文件 */ new webpack.HotModuleReplacementPlugin(), /* 使用了 NoErrorsPlugin 后頁面中的報錯不會阻塞,但是會在編譯結束后報錯 */ new webpack.NoErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin /* 將 index.html 作為入口,注入 html 代碼后生成 index.html文件 */ new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: true }) ] })
webpack.base.conf.js
var path = require('path') // 使用 NodeJS 自帶的文件路徑插件 var config = require('../config') // 引入 config/index.js var utils = require('./utils') // 引入一些小工具 var projectRoot = path.resolve(__dirname, '../') // 拼接我們的工作區路徑為一個絕對路徑 /* 將 NodeJS 環境作為我們的編譯環境 */ var env = process.env.NODE_ENV // check env & config/index.js to decide weither to enable CSS Sourcemaps for the // various preprocessor loaders added to vue-loader at the end of this file /* 是否在 dev 環境下開啟 cssSourceMap ,在 config/index.js 中可配置 */ var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap) /* 是否在 production 環境下開啟 cssSourceMap ,在 config/index.js 中可配置 */ var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap) /* 最終是否使用 cssSourceMap */ var useCssSourceMap = cssSourceMapDev || cssSourceMapProd module.exports = { entry: { app: './src/main.js' // 編譯文件入口 }, output: { path: config.build.assetsRoot, // 編譯輸出的靜態資源根路徑 publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath, // 正式發布環境下編譯輸出的上線路徑的根路徑 filename: '[name].js' // 編譯輸出的文件名 }, resolve: { // 自動補全的擴展名 extensions: ['', '.js', '.vue'], // 不進行自動補全或處理的文件或者文件夾 fallback: [path.join(__dirname, '../node_modules')], alias: { // 默認路徑代理,例如 import Vue from 'vue',會自動到 'vue/dist/vue.common.js'中尋找 'vue$': 'vue/dist/vue.common.js', 'src': path.resolve(__dirname, '../src'), 'assets': path.resolve(__dirname, '../src/assets'), 'components': path.resolve(__dirname, '../src/components') } }, resolveLoader: { fallback: [path.join(__dirname, '../node_modules')] }, module: { preLoaders: [ // 預處理的文件及使用的 loader { test: /\.vue$/, loader: 'eslint', include: projectRoot, exclude: /node_modules/ }, { test: /\.js$/, loader: 'eslint', include: projectRoot, exclude: /node_modules/ } ], loaders: [ // 需要處理的文件及使用的 loader { test: /\.vue$/, loader: 'vue' }, { test: /\.js$/, loader: 'babel', include: projectRoot, exclude: /node_modules/ }, { test: /\.json$/, loader: 'json' }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url', query: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url', query: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } } ] }, eslint: { // eslint 代碼檢查配置工具 formatter: require('eslint-friendly-formatter') }, vue: { // .vue 文件配置 loader 及工具 (autoprefixer) loaders: utils.cssLoaders({ sourceMap: useCssSourceMap }), postcss: [ require('autoprefixer')({ browsers: ['last 2 versions'] }) ] } }
config/index.js
var path = require('path') module.exports = { build: { // production 環境 env: require('./prod.env'), // 使用 config/prod.env.js 中定義的編譯環境 index: path.resolve(__dirname, '../dist/index.html'), // 編譯輸入的 index.html 文件 assetsRoot: path.resolve(__dirname, '../dist'), // 編譯輸出的靜態資源路徑 assetsSubDirectory: 'static', // 編譯輸出的二級目錄 assetsPublicPath: '/', // 編譯發布的根目錄,可配置為資源服務器域名或 CDN 域名 productionSourceMap: true, // 是否開啟 cssSourceMap // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, // 是否開啟 gzip productionGzipExtensions: ['js', 'css'] // 需要使用 gzip 壓縮的文件擴展名 }, dev: { // dev 環境 env: require('./dev.env'), // 使用 config/dev.env.js 中定義的編譯環境 port: 8080, // 運行測試頁面的端口 assetsSubDirectory: 'static', // 編譯輸出的二級目錄 assetsPublicPath: '/', // 編譯發布的根目錄,可配置為資源服務器域名或 CDN 域名 proxyTable: {}, // 需要 proxyTable 代理的接口(可跨域) // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false // 是否開啟 cssSourceMap } }
build.js
// https://github.com/shelljs/shelljs require('./check-versions')() // 檢查 Node 和 npm 版本 require('shelljs/global') // 使用了 shelljs 插件,可以讓我們在 node 環境的 js 中使用 shell env.NODE_ENV = 'production' var path = require('path') // 不再贅述 var config = require('../config') // 加載 config.js var ora = require('ora') // 一個很好看的 loading 插件 var webpack = require('webpack') // 加載 webpack var webpackConfig = require('./webpack.prod.conf') // 加載 webpack.prod.conf console.log( // 輸出提示信息 ~ 提示用戶請在 http 服務下查看本頁面,否則為空白頁 ' Tip:\n' + ' Built files are meant to be served over an HTTP server.\n' + ' Opening index.html over file:// won\'t work.\n' ) var spinner = ora('building for production...') // 使用 ora 打印出 loading + log spinner.start() // 開始 loading 動畫 /* 拼接編譯輸出文件路徑 */ var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory) /* 刪除這個文件夾 (遞歸刪除) */ rm('-rf', assetsPath) /* 創建此文件夾 */ mkdir('-p', assetsPath) /* 復制 static 文件夾到我們的編譯輸出目錄 */ cp('-R', 'static/*', assetsPath) // 開始 webpack 的編譯 webpack(webpackConfig, function (err, stats) { // 編譯成功的回調函數 spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n') })
webpack.prod.conf.js
var path = require('path') // 不再贅述 var config = require('../config') // 加載 confi.index.js var utils = require('./utils') // 使用一些小工具 var webpack = require('webpack') // 加載 webpack var merge = require('webpack-merge') // 加載 webpack 配置合並工具 var baseWebpackConfig = require('./webpack.base.conf') // 加載 webpack.base.conf.js /* 一個 webpack 擴展,可以提取一些代碼並且將它們和文件分離開 */ /* 如果我們想將 webpack 打包成一個文件 css js 分離開,那我們需要這個插件 */ var ExtractTextPlugin = require('extract-text-webpack-plugin') /* 一個可以插入 html 並且創建新的 .html 文件的插件 */ var HtmlWebpackPlugin = require('html-webpack-plugin') var env = config.build.env /* 合並 webpack.base.conf.js */ var webpackConfig = merge(baseWebpackConfig, { module: { /* 使用的 loader */ loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, /* 是否使用 #source-map 開發工具,更多信息可以查看 DDFE 往期文章 */ devtool: config.build.productionSourceMap ? '#source-map' : false, output: { /* 編譯輸出目錄 */ path: config.build.assetsRoot, /* 編譯輸出文件名 */ filename: utils.assetsPath('js/[name].[chunkhash].js'), // 我們可以在 hash 后加 :6 決定使用幾位 hash 值 // 沒有指定輸出名的文件輸出的文件名 chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') }, vue: { /* 編譯 .vue 文件時使用的 loader */ loaders: utils.cssLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, plugins: [ /* 使用的插件 */ // http://vuejs.github.io/vue-loader/en/workflow/production.html /* definePlugin 接收字符串插入到代碼當中, 所以你需要的話可以寫上 JS 的字符串 */ new webpack.DefinePlugin({ 'process.env': env }), /* 壓縮 js (同樣可以壓縮 css) */ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.optimize.OccurrenceOrderPlugin(), // extract css into its own file /* 將 css 文件分離出來 */ new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')), // 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 /* 輸入輸出的 .html 文件 */ new HtmlWebpackPlugin({ filename: config.build.index, template: 'index.html', inject: true, // 是否注入 html 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' }), // split vendor js into its own file /* 沒有指定輸出文件名的文件輸出的靜態文件名 */ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module, count) { // 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', chunks: ['vendor'] }) ] }) /* 開啟 gzip 的情況下使用下方的配置 */ if (config.build.productionGzip) { /* 加載 compression-webpack-plugin 插件 */ var CompressionWebpackPlugin = require('compression-webpack-plugin') /* 向webpackconfig.plugins中加入下方的插件 */ webpackConfig.plugins.push( /* 使用 compression-webpack-plugin 插件進行壓縮 */ new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: new RegExp( '\\.(' + config.build.productionGzipExtensions.join('|') + ')$' ), threshold: 10240, minRatio: 0.8 }) ) } module.exports = webpackConfig