vue-element-admin学习总结(一)

一 前言

1.简介

这是一个极简的 vue admin 管理后台。它只包含了 Element UI & axios & iconfont & permission control & lint,这些搭建后台必要的东西。

 

2.项目地址

建议使用基础模板进行二次开发 :https://github.com/PanJiaChen/vue-admin-template.git

 

3.开始开发

3.1 克隆项目

git clone https://github.com/PanJiaChen/vue-admin-template.git

3.2 进入项目目录

cd vue-admin-template

3.3 安装依赖

npm install

3.4 建议不要直接使用 cnpm 安装以来,会有各种诡异的 bug。可以通过如下操作解决 npm 下载速度慢的问题

npm install --registry=https://registry.npm.taobao.org

3.5  启动服务

npm run dev

 

二  目录结构

├── build                      # 构建相关
├── mock                       # 项目mock 模拟数据
├── plop-templates             # 基本模板
├── public                     # 静态资源
│   │── favicon.ico            # favicon图标
│   └── index.html             # html模板
├── src                        # 源代码
│   ├── api                    # 所有请求
│   ├── assets                 # 主题 字体等静态资源
│   ├── components             # 全局公用组件
│   ├── directive              # 全局指令
│   ├── filters                # 全局 filter
│   ├── icons                  # 项目所有 svg icons
│   ├── lang                   # 国际化 language
│   ├── layout                 # 全局 layout
│   ├── router                 # 路由
│   ├── store                  # 全局 store管理
│   ├── styles                 # 全局样式
│   ├── utils                  # 全局公用方法
│   ├── vendor                 # 公用vendor
│   ├── views                  # views 所有页面
│   ├── App.vue                # 入口页面
│   ├── main.js                # 入口文件 加载组件 初始化等
│   └── permission.js          # 权限管理
├── tests                      # 测试
├── .env.xxx                   # 环境变量配置
├── .eslintrc.js               # eslint 配置项
├── .babelrc                   # babel-loader 配置
├── .travis.yml                # 自动化CI配置
├── vue.config.js              # vue-cli 配置
├── postcss.config.js          # postcss 配置
└── package.json               # package.json

 

三 src下的setings.js文件

  • 可以配置网页标题
  • 可以配置是否在侧边栏显示logo

详细请看代码:

--> src/settings.js

module.exports = {

  title: '花裤衩 后台管理系统基础模板',

  /**
   * @type {boolean} true | false
   * @description Whether fix the header 是否修复头部
   */
  fixedHeader: false,

  /**
   * @type {boolean} true | false
   * @description Whether show the logo in sidebar 是否在侧边栏中显示logo
   */
  sidebarLogo: false
}

 

四  vue.config.js文件配置

vue.config.js是vue-cli 配置文件,是一个可选的配置文件,如果项目的(和package.json 同级的)根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载。

配置选项

  • publicPath 

Type: string

Default: '/'

 部署应用包时的基本 URL, 用法和 webpack 本身的 output.publicPath 一致。

这个值也可以被设置为空字符串 ('') 或是相对路径 ('./'),这样所有的资源都会被链接为相对路径,这样打出来的包可以被部署在任意路径。

  • outputDir

 

  • configureWebpack

Type: Object | Function

如果这个值是一个对象,则会通过 webpack-merge 合并到最终的配置中。

如果这个值是一个函数,则会接收被解析的配置作为参数。该函数及可以修改配置并不返回任何东西,也可以返回一个被克隆或合并过的配置版本。

  • chainWebpack

Type: Function

是一个函数,会接收一个基于 webpack-chain 的 ChainableConfig 实例。允许对内部的 webpack 配置进行更细粒度的修改。

  • devServer

Type: Object

所有 webpack-dev-server 的选项都支持。注意:

有些值像 host、port 和 https 可能会被命令行参数覆写。

有些值像 publicPath 和 historyApiFallback 不应该被修改,因为它们需要和开发服务器的 publicPath 同步以保障正常的工作。

  • devServer.proxy

Type: string | Object

如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置

 

详细注解:

'use strict' // 使用严格
// *  vue-cli 配置文件,是一个可选的配置文件,如果项目的(和package.json 同级的)根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载。

// 1. 引入path模块 拼接文件路径
const path = require('path')

// 2. 引入settings配置文件
const defaultSettings = require('./src/settings.js')

// 1.1 封装拼接方法
function resolve(dir) {
  return path.join(__dirname, dir)
}

// 2.1 获取文件里面的标题
const name = defaultSettings.title || 'vue Admin Template' // page title

// If your port is set to 80,
//  如果您的端口设置为80,
// use administrator privileges to execute the command line.
// 使用管理员权限执行命令行。
// For example, Mac: sudo npm run
// 例如:Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528 // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
// 导出一个包含了选项的对象
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * 如果计划在子路径下部署站点,则需要设置publicPath,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * 例如GitHub页面。如果您计划将站点部署到https://foo.github.io/bar/
   * then publicPath should be set to "/bar/".
   * 那么publicPath应该设置为"/bar/"。
   * In most cases please use '/' !!!
   * 在大多数情况下请使用'/' !!
   * Detail: https://cli.vuejs.org/config/#publicpath
   * 细节:https://cli.vuejs.org/config/ publicpath
   */
  publicPath: '/',  //基本路径
  outputDir: 'dist',  //构建时的输出目录
  assetsDir: 'static', //放置生成的静态资源(js,css,img,fonts)的目录。
  lintOnSave: process.env.NODE_ENV === 'development',   //eslint-loader 是否在保存的时候检查
  productionSourceMap: false,

  // 3. DevServer.proxy : 
  // 如果你的前端应用 和 后端API服务器没有运行在同一个主机上,你需要在开发环境下将API请求代理到API服务器。
  // 这个问题可以通过 vue.config.js 中的 devServer.proxy 来配置。
  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    before: require('./mock/mock-server.js')
  },
  // 4.  webpack相关配置
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // 在webpack的名称字段中提供应用程序的标题,这样
    // it can be accessed in index.html to inject the correct title.
    // 它可以通过index.html来注入正确的标题。
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    }
  },
  // 5.  chainWebpack 是一个函数,会接收一个基于 webpack-china 的chainableConfig 实例,允许对内部的webpack 配置进行更细粒度的修改。
  chainWebpack(config) {
    // it can improve the speed of the first screen, it is recommended to turn on preload
    // 5.1 可以提高第一屏的速度,建议开启预加载
    config.plugin('preload').tap(() => [{
      rel: 'preload',
      // to ignore runtime.js
      // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
      fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
      include: 'initial'
    }])

    // when there are many pages, it will cause too many meaningless requests
    // 5.2 当页面太多时,会导致太多无意义的请求
    config.plugins.delete('prefetch')

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

      // process.env环境变量
    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app 
                  // 重量需要大于libs和app,否则会被打包成libs或app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm   为了适应cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules 可以自定义规则
                  minChunks: 3, //  minimum common number 最低常见的数量
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
          config.optimization.runtimeChunk('single')
        }
      )
  }
}

五 Build文件下的index.js

  • chalk

        chalk是一个 可以修改终端输出字符样式的 npm 包,提高在终端输出的信息的辨识度

  •  process

        process是node的全局模块,作用比较直观。可以通过它来获取node进程相关的信息,比如运行node程序时的命令行参数。或者设置进程相关信息,比如设置环境变量。

  • express

        express连接中间件connect,connect维护了一个中间件栈,栈stack:数据结构,每次调用use,都会向这个应用(app)实例的栈(stack)推入一个带路径和处理函数的对象。

详细注解:

// * 构建相关 build

// 1. 引入 runjs , 可以使用node运行
const {
  run
} = require('runjs')
// 2.  chalk是一个 可以修改终端输出字符样式的 npm 包,提高在终端输出的信息的辨识度
const chalk = require('chalk')

// 3. 引入vue-cli 配置文件
const config = require('../vue.config.js')

// 4. process是node的全局模块,作用比较直观。可以通过它来获取node进程相关的信息,比如运行node程序时的命令行参数。或者设置进程相关信息,比如设置环境变量。
// 4.1  process.argv 获取命令行参数,返回一个数组。
// 参数0: /Users/a/.nvm/versions/node/v6.1.0/bin/node
// 参数1: /Users/a/Documents/argv.js
// 参数2: --env
// 参数3: production
const rawArgv = process.argv.slice(2)
const args = rawArgv.join(' ')

// 4.2 process.env环境变量
if (process.env.npm_config_preview || rawArgv.includes('--preview')) {
  const report = rawArgv.includes('--report')

  run(`vue-cli-service build ${args}`)

  const port = 9526
  // 3.1 引入 配置文件的 基本路径
  const publicPath = config.publicPath

  // 5.  express连接中间件connect,connect维护了一个中间件栈,栈stack:数据结构,每次调用use,都会向这个应用(app)实例的栈(stack)推入一个带路径和处理函数的对象。
  var connect = require('connect')
  // 6. 实现静态资源访问,引入静态资源访问模块,serviceStatic 返回值是一个方法,调用返回的这个方法就可以开启静态资源服务
  var serveStatic = require('serve-static')
  const app = connect()

  app.use(
    publicPath,
    serveStatic('./dist', {
      index: ['index.html', '/']
    })
  )

  app.listen(port, function () {
    // 2.1 终端打印出来的信息,通过 chalk.green() 修改颜色,提高信息辨识度。
    console.log(chalk.green(`> Preview at  http://localhost:${port}${publicPath}`))
    if (report) {
      console.log(chalk.green(`> Report at  http://localhost:${port}${publicPath}report.html`))
    }

  })
} else {
  run(`vue-cli-service build ${args}`)
}

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值