1. 程式人生 > >從vue-cli到打包釋出

從vue-cli到打包釋出

vue-cli初始目錄結構及說明

├── README.md
├── build  編譯任務的程式碼
│   ├── build.js
│   ├── check-versions.js
│   ├── dev-client.js
│   ├── dev-server.js
│   ├── utils.js
│   ├── webpack.base.conf.js
│   ├── webpack.dev.conf.js
│   └── webpack.prod.conf.js
├── config webpack 的配置檔案
│   ├── dev.env.js
│   ├── index.js
│ ├── prod.env.js │ └── test.env.js 自己後加的,測試環境 ├── index.html ├── package.json 專案的基本資訊 ├── src │ ├── App.vue │ ├── assets │ │ └── logo.png │ ├── components │ │ └── Hello.vue │ └── main.js └── static

入口

從 package.json 中我們可以看到

"scripts": {
    "dev": "node build/dev-server.js"
, "build": "node build/build.js", "lint": "eslint --ext .js,.vue src" }

當我們執行 npm run dev / npm run build 時執行的是 node build/dev-server.js 或 node build/build.js

build/dev-server.js

// 檢查 Node 和 npm 版本
require('./check-versions')()
// 獲取 config/index.js 的預設配置
var config = require('../config')

// 如果 Node 的環境無法判斷當前是 dev / product 環境
// 使用 config.dev.env.NODE_ENV 作為當前的環境 if (!process.env.NODE_ENV) process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) // 使用 NodeJS 自帶的檔案路徑工具 var path = require('path') // 使用 express var express = require('express') // 使用 webpack var webpack = require('webpack') // 一個可以強制開啟瀏覽器並跳轉到指定 url 的外掛 var opn = require('opn') // 使用 proxyTable var proxyMiddleware = require('http-proxy-middleware') // 使用 dev 環境的 webpack 配置 var webpackConfig = require('./webpack.dev.conf') // 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() // 啟動 webpack 進行編譯 var compiler = webpack(webpackConfig) // 啟動 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

// 同樣的使用了 config/index.js
var config = require('../config') 
// 使用 webpack
var webpack = require('webpack') 
// 使用 webpack 配置合併外掛
var merge = require('webpack-merge') 
// 使用一些小工具
var utils = require('./utils') 
// 載入 webpack.base.conf
var baseWebpackConfig = require('./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

// 使用 NodeJS 自帶的檔案路徑外掛
var path = require('path') 
// 引入 config/index.js
var config = require('../config') 
// 引入一些小工具
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

index.js 中有 dev 和 production 兩種環境的配置


// see http://vuejs-templates.github.io/webpack for documentation.
// 不再重複介紹了 ...
var path = require('path')
module.exports = {
  // production 環境
  build: { 
    // 使用 config/prod.env.js 中定義的編譯環境
    env: require('./prod.env'), 
    index: path.resolve(__dirname, '../dist/index.html'), // 編譯輸入的 index.html 檔案
    // 編譯輸出的靜態資源根路徑
    assetsRoot: path.resolve(__dirname, '../dist'), 
    // 編譯輸出的二級目錄
    assetsSubDirectory: 'static', 
    // 編譯釋出上線路徑的根目錄,可配置為資源伺服器域名或 CDN 域名
    assetsPublicPath: '/', 
    // 是否開啟 cssSourceMap
    productionSourceMap: true, 
    // 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
    // 是否開啟 gzip
    productionGzip: false, 
    // 需要使用 gzip 壓縮的副檔名
    productionGzipExtensions: ['js', 'css'] 
  },
  // dev 環境
  dev: { 
    // 使用 config/dev.env.js 中定義的編譯環境
    env: require('./dev.env'), 
    // 執行測試頁面的埠
    port: 8080, 
    // 編譯輸出的二級目錄
    assetsSubDirectory: 'static', 
    // 編譯釋出上線路徑的根目錄,可配置為資源伺服器域名或 CDN 域名
    assetsPublicPath: '/', 
    // 需要 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
    cssSourceMap: false 
  }
}

至此,我們的 npm run dev 命令就講解完畢,下面讓我們來看一看執行 npm run build 命令時發生了什麼 ~

build.js

// https://github.com/shelljs/shelljs
// 檢查 Node 和 npm 版本
require('./check-versions')() 
// 使用了 shelljs 外掛,可以讓我們在 node 環境的 js 中使用 shell
require('shelljs/global') 
env.NODE_ENV = 'production'
// 不再贅述
var path = require('path') 
// 載入 config.js
var config = require('../config') 
// 一個很好看的 loading 外掛
var ora = require('ora') 
// 載入 webpack
var webpack = require('webpack') 
// 載入 webpack.prod.conf
var webpackConfig = require('./webpack.prod.conf') 
//  輸出提示資訊 ~ 提示使用者請在 http 服務下檢視本頁面,否則為空白頁
console.log(
  '  Tip:\n' +
  '  Built files are meant to be served over an HTTP server.\n' +
  '  Opening index.html over file:// won\'t work.\n'
)
// 使用 ora 打印出 loading + log
var spinner = ora('building for production...') 
// 開始 loading 動畫
spinner.start() 
// 拼接編譯輸出檔案路徑
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')
// 載入 confi.index.js
var config = require('../config')
// 使用一些小工具
var utils = require('./utils') 
// 載入 webpack
var webpack = require('webpack') 
// 載入 webpack 配置合併工具
var merge = require('webpack-merge') 
// 載入 webpack.base.conf.js
var baseWebpackConfig = require('./webpack.base.conf') 
// 一個 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,
    // 編譯輸出檔名
    // 我們可以在 hash 後加 :6 決定使用幾位 hash 值
    filename: utils.assetsPath('js/[name].[chunkhash].js'), 
    // 沒有指定輸出名的檔案輸出的檔名
    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',
      // 是否注入 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'
    }),
    // 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

開發及打包指令配置

如下圖所示,專案裡只有客戶端程式碼,因此只需要區分不同的打包環境即可,後臺進行jenkins打包時只需要執行對應的指令,前端不需要任何修改
打包指令

dev-server.js

//打包指令後帶引數不同調用不同的webpack打包檔案
var webpackConfig = process.env.NODE_ENV === 'testing'
  ? require('./webpack.prod.conf')
  : require('./webpack.dev.conf')
//當無法使用伺服器的路徑引數來裝載代理,或者需要更多的靈活性,此時代理路徑方式為context
// var context = config.dev.context
// var proxypath = config.dev.proxypath
//
// var options = {
//   target: proxypath,
//   changeOrigin: true,
// }
// if (context.length) {
//   app.use(proxyMiddleware(context, options))
// }

config/index.js

proxyTable: {//反向代理設定(僅適用於開發環境)  知乎單一介面
      '/api': {
        // target: 'http://com', // 生產 -
        target: 'http://com', // 測試 -
        changeOrigin: true,
        // pathRewrite: {
        //   '^/api': '/api/4'
        // }
      },
    },
    // context: [ //確定應將哪些請求代理到目標主機
    //   '/api'
    // ],
    // proxypath: 'http://com',//目標主機到代理

dev.env.js

var merge = require('webpack-merge')
var prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  BASE_API: '"測試api介面地址"',
  APP_ORIGIN: '"測試api介面地址"',
  WX_APP_ID: '"測試微信ID"'
})

prod.env.js

module.exports = {
  NODE_ENV: '"production"',
  BASE_API: '"正式api介面地址"',
  APP_ORIGIN: '"正式api介面地址"',
  WX_APP_ID: '"正式api介面地址"'
}

webpack.base.config.js

路徑簡寫,在元件內可直接呼叫檔案路徑名
resolve: {
    extensions: ['.js', '.vue', '.json'],
    // fallback: [path.join(__dirname, '../node_modules')],
    alias: {
      'src': path.resolve(__dirname, '../src'),
      'api': path.resolve(__dirname, '../src/api'),
      'assets': path.resolve(__dirname, '../src/assets'),
      'components': path.resolve(__dirname, '../src/components'),
      'views': path.resolve(__dirname, '../src/views'),
      'config': path.resolve(__dirname, '../src/config'),
      'util': path.resolve(__dirname, '../src/util'),
      'store': path.resolve(__dirname, '../src/store'),
      'shared': path.resolve(__dirname, '../src/shared'),
      'static': path.resolve(__dirname, '../static'),
      'router': path.resolve(__dirname, '../src/router'),
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
//全域性依賴的第三方js外掛,不建議寫在這裡,加大了打包檔案大小
  plugins:[
    new webpack.ProvidePlugin({
      // $: "jquery",
      // jQuery: "jquery",
      // "window.jQuery": "jquery",
      //"_": "lodash"
    })
  ],

package.json

//此處配置打包檔案指令
 "scripts": {
    "dev": "node build/dev-server.js",
    "build:prod": "cross-env NODE_ENV=production node build/build.js",
    "build:dev": "cross-env NODE_ENV=development npm_config_preview=true  npm_config_report=true node build/build.js",
    "build:test": "cross-env NODE_ENV=testing node build/build.js",
    "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
    "e2e": "node test/e2e/runner.js",
    "test": "npm run unit && npm run e2e"
  },

build.js

打包包檔案大小依賴分析(僅僅測試環境下使用了下)
if(process.env.npm_config_preview){
      server.start({
        port: 9528,
        directory: './dist',
        file: '/index.html'
      });
      console.log('> Listening at ' +  'http://localhost:9528' + '\n')
    }

rem配置

引入淘寶flexible.js,注意此處meta去掉

 <!--<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">-->

百度統計,錯誤日誌統計

    <script>
      var _hmt = _hmt || [];
      (function() {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?0b0ad90031dfa360e567dde3fbfa6e49";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>

後面就是mintUI引入,vuex配置之類的了,大同小異,網上很多教程,就不再贅述了,但是可以推薦下我們的router和vuex配置寫法,感興趣的可以看下,
關於ajax封裝請參考我之前的部落格 基於axios封裝fetch方法及呼叫

router

路由拆分
// 客戶、管理端路由注入
import clientCfg from './router_client'
import managerCfg from './router_manager'
let routes = [
  {path: '/proxy',name:'proxy',component:proxy},
  {path: '/notFound',name:'notFound',component:notFound}
]

routes = new Set([...routes, ...managerCfg, ...clientCfg])

router_client.js

//無非就是路由懶載入之類的
const login = resolve => require(['views/client/login'], resolve)
export default [
  //地址為空時跳轉home頁面
  {
    path: '/',
    redirect: '/client/login'
    // redirect: '/client/demand/list'
  }, {
    path: '/client/login',
    name:'login',
    meta: {pageTitle: '當前頁面title'},
    component: login,
    beforeEnter(to, from, next) {
      if(Storage.get("clientUserToken")) {

      }
      next();
    }
  }

]

vuex

//重寫mutaion方法實現物件方式呼叫
// actions
const actions = {
  // 管理員手機號同步
  [loginUd.A.GET_PHONE]({commit, state}, phone) {
    commit(loginUd.GET_PHONE,phone)
  },
  // 管理員驗證碼同步
  [loginUd.A.GET_CAPTCHA]({commit, state}, captcha) {
    commit(loginUd.GET_CAPTCHA, captcha)
  },
  // 使用者登陸
  [loginUd.A.QUICK_LOGIN]({commit, state}, userInfo = {}) {
    return new Promise(async (resolve, reject) => {
      try {
        const userData = await callAuthLogin(userInfo.userPhone,userInfo.captcha);
        console.log(userData)
        if(!isEmptyObject(userData) && !!userData.user.userToken) {
          Storage.set("clientUserToken", userData.user.userToken)
          commit(loginUd.GET_USER_INFO,userData.user)
          router.push({name: 'home'})
        }
        resolve();
      }catch (error){
        reject(error);
      }
    })
  },
  // 獲取驗證碼
  [loginUd.A.GET_AUTH_CODE]({commit, state}, phone) {
    return new Promise(async (resolve, reject) => {
      try {
        const phoneData = callAuthCode(phone);
        if(phoneData) {
          resolve();
        }
      }catch (error) {
        reject(error);
      }
    })
  }
}

// mutations
const mutations = {
  [loginUd.GET_PHONE](state, phone) {
    state.c_loginDetail.userPhone = phone;
  },
  [loginUd.GET_CAPTCHA](state, captcha) {
    state.c_loginDetail.captcha = captcha;
  },
  [loginUd.GET_USER_INFO](state, userInfo) {
    state.c_loginDetail.user = userInfo;
  }
}

types.js

// 使用者端
export const loginUd = createModules('loginUd', {
  A: ['GET_PHONE', 'GET_CAPTCHA', 'QUICK_LOGIN', 'GET_AUTH_CODE'],
  M: ['GET_PHONE', 'GET_CAPTCHA', 'GET_USER_INFO']
})

相關推薦

vue-cli打包釋出的問題

vue-cli的專案開發完成後,釋出前將進行打包工作,專案資料夾執行npm run build將vue框架編寫的程式轉換為最基礎的html,css,js等。轉換過程中本人遇到了一些問題,整理記錄下: 生成檔案的引號被省略問題: 設定build/webpack.prod.co

vue-cli打包釋出

vue-cli初始目錄結構及說明 ├── README.md ├── build 編譯任務的程式碼 │ ├── build.js │ ├── check-versions.js │ ├── dev-client.js │ ├── dev-

vue-cli 到 webpack多入口打包(一)

從三個外掛開始 1、CommonsChunkPlugin commonsChunkPlugin 是webpack中的程式碼提取外掛,可以分析程式碼中的引用關係然後根據所需的配置進行程式碼的提取到指定的檔案中,常用的用法可以歸為四類:(1)、提取node_modules中的模組到一個檔案中;(2)、提

vue-cli 到 webpack多入口打包(二)

epo 代碼 添加 text dir 例如 arr 向上 只需要 完成多入口打包配置 上一節我說完了三個關鍵的plugin,通過三個plugin我們可以做到將代碼進行分割,並且將分割的代碼打包到我們指定的路徑下,完成打包的模塊可以被index.html文件正確引用。這裏我

vue-cli打包構建時常見的報錯解決方案

imu cli blog error: 背景 服務 strong 背景圖 log 報錯1:打包後丟到服務器中,打開是空白頁 報錯2:打包後想要在本地file中打開,但是打開是空白頁 報錯3:打包後在瀏覽器中打開,報錯ERROR in xxx.js from UglifyJs

vue.js - 解決vue-cli打包後自動壓縮代碼

lena 搜索 .com clas 查看源碼 body 我們 pan hub 當我們用vue腳手架做完項目後,npm run build打包之後, 有沒有查看源碼,全是壓縮好的。但是我就不想讓它壓縮,該怎麽辦呢? 困惑了幾天,查了各種資料。終於終於... 來,上幹貨: 首先

vue-cli 打包後顯示favicon.ico小圖標

cli 文件 技術 vue 相對路徑 alt src 分享 avi 第一步:favicon.ico小圖標放在static裏面 第二步:index.html 文件中引入時需要寫 ./ 相對路徑 第三部:npm run build 打包 打包完成就可以看到

Vue-cli 開始構建 UI 庫到 Markdown 生成文檔和演示案例

fault router 一個 int posit all 運行 save 項目 從 Vue-cli 開始構建 UI 庫到 Markdown 生成文檔和演示案例 1. vue-cli 環境搭建 打開cmd命令工具,輸入npm install -g vue-cli全局安裝

vue-cli 打包 使用 history模式 的後端配置

apach href direct pub htaccess over 指向 -c 路徑 apache的配置 這是windows下的 在httpd-vhosts.conf文件中把目錄指向項目index.html文件所在的位置 # Virtual Hosts # &l

vue-cli 打包編譯 -webkit-box-orient: vertical 被刪除解決辦法

前言 github有人就此問題提問了, 也有了解決辦法, https://github.com/cssnano/cssnano/issues/357, 具體怎麼做,我這裡做一下記錄 正文 原因: -webkit-box-orient: vertical  這個屬性被 optimize-css

關於vue-cli 打包時出現的錯誤

關於vue-cli 打包時出現的錯誤 當我們用vue-cli構建的專案完成之後,就想要在本地上開啟測試效果,此時只需要npm run build 即可( 關於build的配置選項可詳細搜查一下 ), 如果有報錯仔細檢視一下報的錯誤時什麼,如果專案能正常執行一般來講不會報錯,之後會生成di

vue-cli 打包後背景圖出不來解決方法

vue-cli用npm run build打包之後,開啟index.html頁面,背景沒有加載出來解決辦法: 修改build/utils.js檔案裡面的ExtractTextPlugin,新增:publicPath: ‘…/…/’, 具體程式碼如下: if (options.extrac

基於Vue-Cli 打包自動生成/抽離相關配置檔案

背景 基於Vue-cli 專案產品部署,涉及到的互動的地址等配置資訊,每次都要重新打包才能生效,極大的降低了效率。我們的目的是讓專案實施的小夥伴重新快樂起來。網上實現的方式,都是半自動化的,還需要重新修改。 需求點 配置化:打包後的配置檔案可二次修改 配置自動生成:vue-cli 提

vue-cli 打包陷阱

   使用vue-cli 構建完成,編寫完程式碼後進行打包 npm run build  生成 dist 資料夾,裡面有 index.html 檔案,瀏覽器開啟後發現時空白的,問題出現在了打包路徑上。    解決方法:    找到

vue-cli打包優化

打包優化主要是三個方面 下載檔案速度慢 解析JS比較慢 渲染比較慢 服務端渲染(SSR)(伺服器端渲染是載入最快的一種方式) SEO優化 在服務端先將JS進行解析,解析完成之後生成HTML片段,再將HTML返回給前端,前端直接執行渲染介

關於用vue-cli打包dist檔案無法在頁面中訪問

在嘗試用了vue-cli開發專案之後,在專案的最終用npm run build 打包完之後,使用了wamp工具訪問打包的檔案,但是在頁面中顯示所有的連結都沒有都是404. 因此我就查看了index檔案中的所有的外部連結。 之後我就發現了在index檔案裡面 <!D

vue-cli打包後如何執行

執行npm run build進行打包,生成dist資料夾,直接開啟dist中的index.html檔案將會是一片空白 dist中的檔案需要放在伺服器上執行,具體的操作參考上面的部落格,感謝這位博主啦!!! config/index.js中的assetsP

本地測試vue-cli打包後的dist檔案

此方法可以自己本地寫介面,自己打包vue-cli,然後測試打包後的檔案是否正確。 1.本地獲取自己寫到的node.js介面 可能會遇到跨域的問題,可以看我的部落格跨域問題 1.1.在vue頁面中引入自己node.js寫的介面(關於node.js的教

使用vue-cli打包過程中的步驟以及問題

1、打包命令是npm run build,這個命令實際上是在package.json中,scripts中build所對應的命令; 2、建立一個prod.server.js,這個檔案不是必須的,這個檔案的用處是在打包完畢之後,通過啟動node.js本地服務來訪問打包完成

關於vue-cli打包後,index顯示空白頁解決方法

1.修改打包時,檔案引用路徑在config檔案加下index.js檔案中,找到 build 中的  assetsPublicPath 將 assetsPublicPath: '/' 修改為 assetsPublicPath: './'  即新增一個點2.註釋相關列印提示(可選