vue项目引入svg组件全过程

文件格式

svg下方对应 .svg

index.vue svg-icon 组件

js 复制代码
<template>
  <svg
    :viewBox="viewBox"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    ref="svg"
    class="svg-icon"
    :class="className"
    v-on="$listeners"
    :style="{ width: width + 'em', height: height + 'em' }"
    v-html="iconContent"
  ></svg>
</template>

<script>
export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ''
    },
    width: {
      type: Number,
      default: 1
    },
    height: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      iconContent: null,
      viewBox: '0 0 24 24',
      test: ''
    }
  },
  watch: {
    iconClass() {
      this.loadIcon()
    }
  },
  created() {
    this.loadIcon()
  },
  methods: {
    loadIcon() {
      const fileName = `${this.iconClass}.svg`
      import(`@/icons/svg/${fileName}`).then((content) => {
        // symbol转换成svg
        const regexSymbol = /<symbol(\s[\s\S]*?)?>([\s\S]*?)<\/symbol>/g
        const svg = content.default.content.replace(regexSymbol, '<svg$1>$2</svg>')
        this.test = content
        // 获取svg内标签
        const regexSvg = /<svg([\s\S]*?)?>([\s\S]*?)<\/svg>/g
        const match = regexSvg.exec(svg)
        this.iconContent = match[2]

        // 匹配svg属性
        const regexAttr = /<svg([\s\S]*?)?>/
        const matchAttr = regexAttr.exec(svg)[1].trim()
        const viewBoxReg = /viewBox="([^"]+)"/
        const viewBoxValue = viewBoxReg.exec(matchAttr)[1]
        this.viewBox = viewBoxValue
      }).catch((err)=>{
        console.log(err)
      })
    }
  }
}
</script>

<style scoped>
.svg-icon {
  /* width: 2em;
  height: 2em; */
  vertical-align: -0.15em;
  fill: currentColor !important;
  overflow: hidden;
}
</style>

index.js 注册组件

js 复制代码
import Vue from 'vue'
// import SvgIcon from '@/components/SvgIcon' // svg组件
import SvgIcon from './index.vue' // svg组件

// register globally
Vue.component('SvgIcon', SvgIcon)

// const requireAll = (requireContext) => requireContext.keys().map(requireContext)
// const req = require.context('./svg', false, /\.svg$/)
// export default requireAll(req)

主要是这段

js 复制代码
 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();

安装npm i svg-sprite-loader

js 复制代码
"svg-sprite-loader": "^6.0.11",

补充 可以不看

  • vue.config.js 主要使用带svg的那一段 这是webapck5 的配置

    const { defineConfig } = require("@vue/cli-service");
    const speedMeasureWebpackPlugin = require("speed-measure-webpack-plugin"); // 编译速度分析
    const smp = new speedMeasureWebpackPlugin();
    const path = require("path");
    const isProd = process.env.NODE_ENV === "production";
    let plugins = [];

    module.exports = defineConfig({
    productionSourceMap: false,
    transpileDependencies: true,
    lintOnSave: false,
    devServer: {
    port: 8080,
    open: true,
    hot: true,
    allowedHosts: 'all',
    compress: true, // 是否启动压缩Gzip
    client: {
    overlay: {
    errors: true,
    warnings: false,
    runtimeErrors: false
    }
    },

    复制代码
      }
    },
    configureWebpack: smp.wrap({
      devtool: isProd ? false : "eval", // source-map eval-cheap-module-source-map
      cache: {
        type: "filesystem",
        allowCollectingMemory: true,
        buildDependencies: {
          config: [__filename],
        },
      },
      plugins: plugins,
      optimization: {
        minimize: isProd,
        splitChunks: {
          chunks: "all",
          cacheGroups: {
            common: {
              name: "chunk-common",
              chunks: "initial",
              minChunks: 2,
              maxInitialRequests: 5,
              minSize: 0,
              priority: 1,
              reuseExistingChunk: true,
              enforce: true,
            },
            vendors: {
              name: "chunk-vendors",
              test: /[\\/]node_modules[\\/]/,
              chunks: "initial",
              priority: 2,
              reuseExistingChunk: true,
              enforce: true,
            },
            elementUI: {
              name: "chunk-elementui",
              test: /[\\/]node_modules[\\/]element-ui[\\/]/,
              chunks: "all",
              priority: 3,
              reuseExistingChunk: true,
              enforce: true,
            },
            vuedraggable: {
              name: "chunk-vuedraggable",
              test: /[\\/]node_modules[\\/]vuedraggable[\\/]/,
              chunks: "all",
              priority: 8,
              reuseExistingChunk: true,
              enforce: true,
            },
            zrender: {
              name: "chunk-zrender",
              test: /[\\/]node_modules[\\/]zrender[\\/]/,
              chunks: "all",
              priority: 10,
              reuseExistingChunk: true,
              enforce: true,
            },
          },
        },
      },
      module: {
        rules: [],
      },
    }),
    chainWebpack(config) {
      if (!isProd) {
        config.optimization.minimizers.delete("terser");
        config.optimization.minimizers.delete("css");
        config.module
          .rule("js")
          .test(/\.jsx$/)
          .exclude.add(/node_modules/)
          .end();
        config.module
          .rule("jsEsbuild")
          .test(/\.js$/)
          .exclude.add(/node_modules/)
          .end()
          .use("esbuild")
          .loader("esbuild-loader")
          .options({
            loader: "js",
            target: "es2015",
          })
          .end();
      }
    
      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();
      config.plugin("html").tap((args) => {
        const date = new Date().toLocaleString();
        args[0].createDate = date;
        return args;
      });
    },

    });

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

相关推荐
web打印社区21 分钟前
Windows 网页静默打印设置步骤:客户端、防火墙与联调清单
开发语言·前端·javascript·chrome·pdf·ecmascript
web打印社区1 小时前
JS 静默打印怎么做:纯前端为什么不行,以及最小可跑通写法
开发语言·前端·javascript·websocket·网络协议·http·pdf
web打印社区1 小时前
HTML5 静默打印:前端页面怎么调用打印机且尽量不弹窗
前端·javascript·vue.js·pdf·html·html5
liangshanbo12152 小时前
React Fiber:从“解决卡顿”到完整更新链路
前端·javascript·react.js
雪芽蓝域zzs2 小时前
第3节:el-select 弹窗定位、滚动穿透与挂载容器(popper-append-to-body /teleported)
vue.js·elementui
铅笔小新z3 小时前
【stm32】理解弱引用
javascript·stm32·嵌入式硬件
凤城老人4 小时前
从PyQt6到Electron:一款英语字帖生成器的跨平台重构实战与踩坑全记录
javascript·重构·electron
雪芽蓝域zzs12 小时前
第 2 节:基础扩展 - 下拉弹窗常用原生属性
vue.js·elementui
星栈15 小时前
pnpm 12 升级实测
前端·javascript
Ai-_Man16 小时前
您您这可以把Microsofat Copilot的多个会话比如说。左侧的多个会话一次性导出吗?不是单条会话里面的多次会对话。AI导出鸭
javascript·人工智能·ai·小程序·电脑·copilot