探索 vue-spa 全家桶專案,解析配置,目錄結構,路由以及狀態管理的實現,附原始碼

小錢錢阿聖發表於2017-08-14

1.簡介

專案是一個簡單的許可權管理頁面,分為3個頁面,
首頁,賬戶中心,登入頁
通過vue-router 對於路由做許可權控制,
首頁無需登入,跳轉賬戶中心會自動檢索是否登入,
登入之後首頁的登入按鈕變為退出按鈕,
頁面之間的的狀態管理全部通過vuex進行管理

專案演示

專案用到的技術棧:
  • vue
  • vue-router
  • vuex
  • webpack
  • axios
  • eslint
  • less

github地址

基礎環境

node : v8.2.1
npm : 5.3.0

注:如果專案install有問題,可把對應環境配置成上面相關的環境在嘗試

專案執行

$ npm install
$ npm run dev複製程式碼

2.目錄結構

├── README.md                       專案介紹
├── index.html                      入口頁面
├── build                           構建指令碼目錄
│   ├── webpack.base.conf.js            webpack基礎配置,開發環境,生產環境都依賴   
│   ├── webpack.dev.conf.js             webpack開發環境配置
│   ├── webpack.prod.conf.js            webpack生產環境配置
│   ├── build.js                        生產環境構建指令碼               
│   ├── dev-server.js                   開發伺服器熱過載指令碼,主要用來實現開發階段的頁面自動重新整理
│   ├── utils.js                        構建相關工具方法
├── config                          專案配置
│   ├── dev.env.js                      開發環境變數
│   ├── index.js                        專案配置檔案
│   ├── prod.env.js                     生產環境變數
├── src                             原始碼目錄    
│   ├── main.js                         入口檔案
│   ├── config                          入口相關配置檔案
│   ├── app.vue                         根元件
│   ├── components                      公共元件目錄
│   │   └── base                          基礎元件
│   │   └── layouts                       佈局元件
│   │       └──header                       頭部元件
│   │           └──index.vue
│   │           └──index.less            
│   ├── styles                          樣式資源
│   │   └── index.less                    樣式入口
│   │   └── var.less                      變數
│   │   └── reset.less                    重置樣式  
│   │   └── common.less                   公共樣式  
│   ├── images                          圖片資源
│   │   └── auth                          驗證模組圖片
│   ├── pages                           頁面目錄
│   │   └── auth                          驗證模組
│   │       └── login                       登入檔案
│   │           └── index.vue                 登入頁
│   │           └── index.less                登入頁樣式
│   ├── routes                          路由目錄
│   │   └── auth                          驗證模組
│   │       └── index.js                    驗證模組入口
│   │   └── index                         所有模組彙總
│   ├── store                           應用級資料(state)
│   │   └── index.js                      所有模組資料彙總
│   │   └── auth                          驗證相關資料模組
│   │       └── index.js                    驗證模組入口
│   │       └── mutation-types.js           型別
│   │       └── actions.js                  actions
│   │       └── mutations.js                mutations
│   │       └── getters.js                  getters
│   │       └── state.js                    預設狀態
│   ├── services                        介面api定義
├── .eslintrc.js                        eslint規則配置
├── package.json複製程式碼

大概解釋一下目錄結構

專案是以模組化去劃分頁面,
建議在拿到需求的時候,根據模組劃分好頁面,
定義好模組名稱,建議pages,images,routes目錄,模組名保持一致,
pages目錄裡面是模組檔案,模組檔案裡面是頁面檔案,
頁面檔案包含實現還有樣式檔案
styles目錄裡面放一些公共樣式,最後通過index.less匯出,在入口檔案引入
components目錄裡面放幾個模組,可以大致分為base基礎元件,
layouts佈局元件,bussiness業務元件,然後在對應模組下面寫上對應的元件實現


3.配置檔案

package.json裡面的配置

"dev": "node build/dev-server.js",
"build": "node build/build.js",複製程式碼

3.1開發環境啟動 dev-server.js

dev-server.js的實現

require('./check-versions')()

var config = require('../config')
if (!process.env.NODE_ENV) {
  process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}

var opn = require('opn')
var path = require('path')
var express = require('express')
var webpack = require('webpack')
var proxyMiddleware = require('http-proxy-middleware')
var webpackConfig = require('./webpack.dev.conf')

// default port where dev server listens for incoming traffic
var port = process.env.PORT || config.dev.port
// automatically open browser, if not set will be false
var autoOpenBrowser = !!config.dev.autoOpenBrowser
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
var proxyTable = config.dev.proxyTable

var app = express()
var compiler = webpack(webpackConfig)

var devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
  quiet: true
})

var hotMiddleware = require('webpack-hot-middleware')(compiler, {
  log: () => {
  }
})
// 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
Object.keys(proxyTable).forEach(function (context) {
  var options = proxyTable[context]
  if (typeof options === 'string') {
    options = { target: options }
  }
  app.use(proxyMiddleware(options.filter || context, options))
})

// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())

// serve webpack bundle output
app.use(devMiddleware)

// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)

// serve pure static assets
var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
app.use(staticPath, express.static('./static'))

var uri = 'http://localhost:' + port

var _resolve
var readyPromise = new Promise(resolve => {
  _resolve = resolve
})

console.log('> Starting dev server...')
devMiddleware.waitUntilValid(() => {
  console.log('> Listening at ' + uri + '\n')
  // when env is testing, don't need open it
  if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
    opn(uri)
  }
  _resolve()
})

var server = app.listen(port)

module.exports = {
  ready: readyPromise,
  close: () => {
    server.close()
  }
}複製程式碼

dev-server.js依賴了webpack.dev.conf.js配置檔案
配置檔案分為webpack.base.conf.js基礎配置
還有webpack.dev.conf.js開發環境的配置
還有webpack.prod.conf.js生產環境的配置

貼一段base的基礎配置

var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')

function resolve(dir) {
  return path.join(__dirname, '..', dir)
}

module.exports = {
  entry: {
    app: ['babel-polyfill', './src/main.js']
  },
  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: {
      '@': resolve('src'),
      '~component': resolve('src/components'),
    }
  },
  module: {
    rules: [
      // eslint檢查配置 不需要可以註釋
      {
        test: /\.(js|vue)$/,
        loader: 'eslint-loader',
        enforce: 'pre',
        include: [resolve('src'), resolve('test')],
        options: {
          formatter: require('eslint-friendly-formatter')
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  plugins: [
  ]
}複製程式碼

上面的配置依賴於config目錄的一些配置,
config目錄分為prod.evn.js生產環境的變數,dev.env.js 開發環境的變數,
比如api介面的地址就可以在這邊配置,根據開發環境還有生產環境分別配置不同的介面地址

config入口檔案的實現

// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: './',
    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
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    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
  }
}複製程式碼

入口檔案根據環境的不同,分別做了一些不同的配置

貼一段dev的配置

var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})

module.exports = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: '#cheap-module-eval-source-map',
  plugins: [
    new webpack.DefinePlugin({
      'process.env': config.dev.env
    }),
    // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    new FriendlyErrorsPlugin()
  ]
})複製程式碼

3.2生產環境啟動 build.js

build.js的實現

require('./check-versions')()

process.env.NODE_ENV = 'production'

var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')

var spinner = ora('building for production...')
spinner.start()

rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err
  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\n')

    console.log(chalk.cyan('  Build complete.\n'))
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))
  })
})複製程式碼

build引入了webpack.prod.conf,下面貼一段實現prod的實現

var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

var env = config.build.env

var webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : 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 webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css')
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        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: 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'
    }),
    // 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']
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  var 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) {
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig複製程式碼

上面分別是dev環境還有prod環境的配置,
他們都是基礎base配置,不同點主要在於

  • dev環境利用express在本地搭建了環境,啟動了熱更新服務
  • prod環境js,html進行了壓縮合並,減少了體積
  • prod環境提取了公共js,提取了樣式檔案

4.路由的實現

使用vue-router進行單頁面路由的控制

vue-router的相關概念介紹,就不一一介紹的,這邊直接講解vue-router在專案中的實現,具體的vue-router相關知識請參考vue-router官網
路由的使用在config.js檔案中

export const router = new VueRouter({
  mode: 'history',
  routes,
});複製程式碼

mode為history表示使用h5 history模式,這樣就不會出現#符號

不過history模式下面也有一些坑,具體可以參考
HTML5 History 模式

路由目錄如下:

│   ├── routes                          路由目錄
│   │   └── auth                          驗證模組
│   │       └── index.js                    驗證模組入口
│   │   └── index                         所有模組彙總複製程式碼

路由模組按照頁面模組同步,如驗證模組,保持跟頁面模組一致,
一個模組下面放一個模組入口,裡面的配置如下

const Login = r => require.ensure([], () => r(require('@/pages/auth/login')), 'auth');
const arr = [
  {
    path: '/login',
    name: 'login.index',
    component: Login,

    // If the user needs to be a guest to view this page
    meta: {
      guest: true,
    },
  },
];
// Auth
export default arr;複製程式碼
const Login = r => require.ensure([], () => r(require('@/pages/auth/login')), 'auth');複製程式碼

這邊結合 Vue 的 非同步元件和 Webpack 的 code splitting feature, 輕鬆實現路由元件的懶載入。
有時候我們想把某個模組下的所有元件都打包在同個非同步 chunk 中。只需要提供 require.ensure第三個引數作為 chunk 的名稱即可


路由做了許可權控制,對於需要登入之後才能開啟的頁面,
我們控制meta.auth 屬性為true即可

export const router = new VueRouter({
  mode: 'history',
  routes,
});
router.beforeEach((to, from, next) => {
  if (to.matched.some(m => m.meta.auth) && !store.state.auth.authenticated) {
    /*
     * If the user is not authenticated and visits
     * a page that requires authentication, redirect to the login page
     */
    next({
      name: 'login.index',
    });
  } else if (to.matched.some(m => m.meta.guest) && store.state.auth.authenticated) {
    /*
     * If the user is authenticated and visits
     * an guest page, redirect to the dashboard page
     */
    next({
      name: 'home.index',
    });
  } else {
    next();
  }
});複製程式碼

5.Vuex狀態管理

專案使用vuex進行狀態管理,把一些公共行為,api互動相關的狀態都封裝在vuex中進行統一管理

vuex的相關概念介紹,就不一一介紹的,這邊直接講解vuex在專案中的實現,具體的vuex相關知識請參考vuex官網

vuex目錄實現:

│   ├── store                           應用級資料(state)
│   │   └── index.js                      所有模組資料彙總
│   │   └── auth                          驗證相關資料模組
│   │       └── index.js                    驗證模組入口
│   │       └── mutation-types.js           型別
│   │       └── actions.js                  actions
│   │       └── mutations.js                mutations
│   │       └── getters.js                  getters
│   │       └── state.js                    預設狀態複製程式碼

vuex按照資料模型進行劃分
注: 這邊的模組名稱不必與頁面模組相同,按照資料模型劃分更為合理

這邊簡單介紹一下自己對於vuex流程的理解

1.首先就是我們在頁面上必須通過action(行為)去改變資料狀態,那麼我們就需要定義action
/* ============
 * Actions for the auth module
 * ============
 *
 * The actions that are available on the
 * auth module.
 */

import * as types from './mutation-types';
import Vue from 'vue';
import store from '@/store';

export const check = (
  { commit }) => {
  commit(types.CHECK);
};

export const login = ({ commit }, payload) => {
  /*
   * Normally you would perform an AJAX-request.
   * But to get the example working, the data is hardcoded.
   *
   * With the include REST-client Axios, you can do something like this:
   * Vue.$http.post('/auth/login', user)
   *   .then((response) => {
   *     success(response);
   *   })
   *   .catch((error) => {
   *     failed(error);
   *   });
   */
  const promise = new Promise((resolve, reject) => {
    const success = true;
    if (success) {
      commit(types.LOGIN, payload);
      // 登入成功,觸發存入使用者資訊
      store.dispatch('account/setAccount');
      Vue.router.push('/account');
      resolve();
    } else {
      reject();
    }
  });
  return promise;
};

export const logout = ({ commit }) => {
  const promise = new Promise((resolve, reject) => {
    const success = true;
    if (success) {
      commit(types.LOGOUT);
      resolve();
    } else {
      reject();
    }
  });
  return promise;
};

export default {
  check,
  login,
  logout,
};複製程式碼
2.更改 Vuex 的 store 中的狀態的唯一方法是提交 mutation (變化)

每個 mutation 都有一個字串的 事件型別 (type) 和 一個 回撥函式 (handler)

/* ============
 * Mutations for the auth module
 * ============
 *
 * The mutations that are available on the
 * account module.
 */

import Vue from 'vue';
import {
  CHECK,
  LOGIN,
  LOGOUT,
} from './mutation-types';

export default {
  [CHECK](state) {
    state.authenticated = !!localStorage.getItem('id_token');
    if (state.authenticated) {
      Vue.$http.defaults.headers.common.Authorization = `Bearer ${localStorage.getItem('id_token')}`;
    }
  },

  [LOGIN](state, token) {
    state.authenticated = true;
    localStorage.setItem('id_token', token);
    Vue.$http.defaults.headers.common.Authorization = `Bearer ${token}`;
  },

  [LOGOUT](state) {
    state.authenticated = false;
    localStorage.removeItem('id_token');
    Vue.$http.defaults.headers.common.Authorization = '';
  },
};複製程式碼
3.mutation需要事件型別,那麼我們就需要定義一個不可變的型別,這樣可以避免型別衝突
/* ============
 * Mutation types for the account module
 * ============
 *
 * The mutation types that are available
 * on the auth module.
 */

export const CHECK = 'CHECK';
export const LOGIN = 'LOGIN';
export const LOGOUT = 'LOGOUT';

export default {
  CHECK,
  LOGIN,
  LOGOUT,
};複製程式碼
4.那麼前面的資料變更都完成了,如何獲取資料的變更了,這時候我們就需要getters了
/* ============
 * Getters for the auth module
 * ============
 *
 * The getters that are available on the
 * auth module.
 */

export default {
  isLogin: state => state.authenticated,
};複製程式碼
5.資料初始化的時候都為空,這時候我們要定義一些預設的狀態,就需要state了
/* ============
 * State of the auth module
 * ============
 *
 * The initial state of the auth module.
 */

export default {
  authenticated: false,
};複製程式碼
6.最後就是把當前模組匯出了,在index裡面實現
/* ============
 * Auth Module
 * ============
 */

import actions from './actions';
import getters from './getters';
import mutations from './mutations';
import state from './state';

export default {
  namespaced: true,
  actions,
  getters,
  mutations,
  state,
};複製程式碼
7.在頁面上如何繫結action還有獲取getter呢?
import { mapActions, mapGetters } from 'vuex';
...
computed: {
      ...mapActions({
        authLogout: 'auth/logout', // 對映 this.authLogout() 為 this.$store.dispatch('auth/logout')
      }),
      // 使用物件展開運算子將 getters 混入 computed 物件中
      ...mapGetters({
        // 對映 this.auth/isLogin 為 store.getters.auth/isLogin
        isLogin: 'auth/isLogin',
      }),
    },複製程式碼

我們通過mapGetters,mapActions輔助函式去實現

6.eslint在專案中的使用

專案整合了eslint,做程式碼規範的檢查
專案的eslint目前繼承了airbnb提供的規則驗證

注:目前eslint整合在webpack環境中,專案啟動的時候,如果有相關格式不符合規則,就會提示錯誤,這樣的方案可能有些人不是很適應,那麼可以通過註釋下面的程式碼關閉eslint在webpack啟動期間的執行
在webpack.base.conf.js中配置

// eslint檢查配置 不需要可以註釋
      {
        test: /\.(js|vue)$/,
        loader: 'eslint-loader',
        enforce: 'pre',
        include: [resolve('src'), resolve('test')],
        options: {
          formatter: require('eslint-friendly-formatter')
        }
      },複製程式碼

不過個人建議還是在專案中整合eslint,好的程式碼習慣和風格,對於專案的閱讀性,後期維護性還有擴充套件性都有很大的幫助

eslint可以加入一些自己個人的規則配置,在.eslintrc.js檔案下修改,如下:

// http://eslint.org/docs/user-guide/configuring

module.exports = {
  root: true,
  parser: 'babel-eslint',
  parserOptions: {
    sourceType: 'module'
  },
  env: {
    browser: true,
  },
  extends: 'airbnb-base',// 繼承aribnb的配置
  // required to lint *.vue files
  plugins: [
    'html'
  ],
  // check if imports actually resolve
  'settings': {
    'import/resolver': {
      'webpack': {
        'config': 'build/webpack.base.conf.js'
      }
    }
  },
  // add your custom rules here 0表示關閉規則
  'rules': {
    'global-require': 0,
    'import/first': 0,
    'no-console': 0,
    'no-param-reassign': 0,
    'no-multi-assign': 0,

    // don't require .vue extension when importing
    'import/extensions': ['error', 'always', {
      'js': 'never',
      'vue': 'never'
    }],
    // allow optionalDependencies
    'import/no-extraneous-dependencies': ['error', {
      'optionalDependencies': ['test/unit/index.js']
    }],
    // allow debugger during development
    'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
  }
}複製程式碼

更多eslint規則請參考

eslint一鍵格式化

npm run lint複製程式碼

執行上面命令就會根據eslint設定的規則格式化,建議在關閉eslint的同學,在上傳程式碼之前都執行一下這個命令,這樣可以保證大家程式碼風格的統一性

eslint官網,更多eslint相關知識請檢視

7.命名規範

元件樣式命名: 統一採用 we(根據自己定製) 字首 如: we-header
頁面樣式命名: 統一採用 page(根據自己定製) 字首 如: page-login
檔案命名: 統一採用-命名方式: 如: user-help
樣式命名: 統一採用-命名方式: 如: .user-help
圖片命名: 統一採用-命名方式: 如: .icon-help.png

8.總結

一個專案在初期框架選型的時候,就需要把目錄結構,對應的命令規則,模組劃分好,團隊成員保持一樣的程式碼風格去實現功能,這樣後期的擴充套件性,健壯性才會比較好
所以在專案初期階段,一定需要花一些時間與團隊人員一起思考總結,把這些東西考慮到位
目前專案沒有整合元件庫,你可以根據自己的需要去整合一個符合自己專案的元件庫
上面都是我自己目前在新專案中的一些思考,你可以根據你自己的喜好還有想法去做一些改進,希望可以給你一些幫助,如果有更好的建議歡迎一起留言討論,感謝!!!

相關文章