六、项目最近实践 ---kkb

项目配置

配置文件入口: vue.config.js

做一些基础配置:指定应用上下文、端口号、title

// vue.config.js
const port = 7070
const title = 'vue项目最佳实践'

module.exports = {
  publicPath: '/best-practice', // 部署应⽤用包时的基本 URL 
  devServer: {
    port
  },
  configureWebpack: {
    // 向index.html注⼊入标题
    name: title
  }
}


// index.html
<title><%= webpackConfig.name %></title>

命令:vue inspect   可以拿到整个webpack的全部配置

命令:vue inspect --rules   查看当前项目下所有的规则

命令:vue inspect --rule vue   查看vue的规则(也可以查看其他的规则,例如 svg)

链式操作:演示webpack规则配置

范例:项目要使用icon,传统方案是图标字体(字体文件+样式文件),不便维护;svg方案采用 svg-sprite-loader 自动加载打包,方便维护

使用icon前先安装依赖:svg-sprite-loader

npm i svg-sprite-loader -D 

下载一个svg图标,  存入  /src/icons/svg  中,例如: /src/icons/svg/wx.svg

修改规则和新增规则,vue.config.js

const path = require('path')
// 将传入的相对路径转换为绝对路径
function resolve(dir){
  return path.join(__dirname, dir)
}

chainWebpack(config) {
  // 配置svg规则排除icons⽬目录中svg⽂文件处理理
  config.module.rule('svg')
    .exclude.add(resolve('src/icons'))
  
  // 新增icons规则,设置svg-sprite-loader处理理icons⽬目录中的svg 
  config.module.rule('icon') //新增icons规则 
    .test(/\.svg$/) // 设置test选项
    .include.add(resolve('src/icons')) // 加入include,include选项是数组
      .end() //add完上下⽂是include数组不是icons规则,使⽤end()回退 
    .use('svg-sprite-loader') // 添加loader
      .loader('svg-sprite-loader') // 切换上下文为 svg-sprite-loader
      .options({ symbolId: 'icon-[name]' }) // 指定选项,如果到时候图片名称是 wx.svg,这里就是 icon-wx
      .end() // 回退
}

在组件中使用

<svg>
  <use xlink:href="#icon-wx"></use>
</svg>

import '@/icons/svg/wx.svg'

我们发现使用方式比较繁琐:

1、将<svg>建一个组件

2、自动导入

图标自动导入

//  src/icons/index.js 
// 利用webpack的require.context 自动导入
// 返回的req是只去加载svg目录中的模块的函数
// 参数2:不要继续往下递归,参数3:匹配的规则
const req = require.context('./svg', false, /\.svg$/)

// 遍历加载上下文中所有项 
req.keys().map(req)


// main.js
import './icons'

封装组件

创建组件 Icon    /components/Icon.vue

<template>
  <svg :class="svgClass" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName" />
  </svg>
</template>
<script> 
export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ''
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`
    },
    svgClass() {
      if (this.className) {
        return 'svg-icon ' + this.className
      } else {
        return 'svg-icon'
      }
    }
  }
}
</script>
<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

修改 /icon/index.js 文件,加入以下代码

import Vue from 'vue';
import Icon from '@/components/Icon'

// Icon组件全局注册一下
Vue.component('Icon', Icon)

组件中修改使用方法

<Icon icon-class="qq" />
<Icon icon-class="wx" />

猜你喜欢

转载自www.cnblogs.com/haishen/p/11821879.html