How to use svg icon in Nuxt.js? And the difference between nuxt.js and vue.js using svg icons

First introduce Nuxt.js: Nuxt.js is a lightweight framework based on Vue.js, which can be used to create server-side rendering (SSR) applications, and it can also be used to generate static sites.

Official website: https://nuxtjs.org/

Using Nuxt.js for server-side rendering is more conducive to SEO. This is the biggest reason I use Nuxt.js.

However, there are still many differences between the project structure and some configuration writing of Nuxt.js and the vue-cli project I usually write, so I wrote this article to record the process of using svg icons in Nuxt.js.

Where can I find free svg icon resources?
Alibaba vector icon library: https://www.iconfont.cn/

First of all, there are three steps to use svg in nuxt:


1. Create a vue component

First, nuxt project directory componentsis established SvgIcon.vue, the following code

<template>
  <svg
    :class="svgClass"
    aria-hidden="true"
  >
    <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 () {
     
     
      return this.className ? 'svg-icon ' + this.className : 'svg-icon'
    }
  }
}
</script>

<style scoped>
.svg-icon {
     
     
  width: 1em;
  height: 1em;
  font-size: 1.2em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

2. Create Nuxt plugin file

Create a directory under the project directory plugins, and then create a icons.jsfile in it, the code is as follows:

import Vue from 'vue'
// 引用组件
import SvgIcon from '@/components/SvgIcon.vue'

// 注册全局组件,组建名为svg-icon
Vue.component('svg-icon', SvgIcon)

// 引用svg图标
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('@/assets/svg', true, /\.svg$/)
requireAll(req)

Note here:

// 引用项目 assets/svg 目录下的所有 .svg 文件
// 如果第二个参数为 true ,程序将会遍历 assets/svg 目录下的子目录,并引用其中的 .svg 文件
// 如果不需要遍历子目录,可设为 false 
const req = require.context('@/assets/svg', true, /\.svg$/)

Remember to create a directory under the project directory assets/svg, this directory will be used to store .svgfiles

3. Configure nuxt.config.js

This svg-sprite-loaderdependency is used in this step , first install it with npm:

npm install svg-sprite-loader --save-dev

Then open it nuxt.config.jsand add at the top:

// eslint-disable-next-line nuxt/no-cjs-in-config
const path = require('path')

Then modify the buildpart and configure webpack:

  /*
  ** Build configuration
  ** See https://nuxtjs.org/api/configuration-build/
  */
  build: {
    
    
    extend (config, ctx) {
    
    
      // ...
      const svgRule = config.module.rules.find(rule => rule.test.test('.svg'))
      svgRule.exclude = [path.resolve(__dirname, 'assets/svg')]
      // Includes /icons/svg for svg-sprite-loader
      config.module.rules.push({
    
    
        test: /\.svg$/,
        include: [path.resolve(__dirname, 'assets/svg')],
        loader: 'svg-sprite-loader',
        options: {
    
    
          symbolId: 'icon-[name]'
        }
      })
    }
  }

Last modified pluginspart:

  /*
  ** Plugins to load before mounting the App
  ** https://nuxtjs.org/guide/plugins
  */
  plugins: [
    {
    
     src: '@/plugins/icons', ssr: true }
  ],

That's it. Restart the project, and assets/svgput your .svgfiles in the directory , you can reference in the project.

Reference method:

<svg-icon icon-class="heart-fill" />

Here icon-classis your .svgfile name, .vuejust call it directly in the file (remember to assets/svgput the .svgicon in the directory first )


The difference with the vue-cli project:

Mainly there are some differences between the second创建Nuxt插件文件 and third steps配置nuxt.config.js and the configuration of the vue-cli project.

In the vue-cli project, we can directly main.jsuse it in the file Vue.component('svg-icon', SvgIcon)for global component registration.

In the nuxt project, we not only need pluginsto create plug-in files in the directory for component registration, but also need to add plug-in files nuxt.config.jsin the pluginsconfiguration items.

Are there more steps?

When configuring webpack in the third step, I usually write this in the vue-cli project:

vue.config.js


module.exports = {
    
    
	chainWebpack: config => {
    
    
	    // svg config
	    const svgRule = config.module.rule('assets/svg')
	    svgRule.uses.clear()
	    svgRule.use('svg-sprite-loader').loader('svg-sprite-loader')
	      .options({
    
    
	        symbolId: 'icon-[name]'
	      })
	  }
}

In the nuxt.js project, it becomes:

nuxt.config.js

  build: {
    
    
    extend (config, ctx) {
    
    
      // ...
      const svgRule = config.module.rules.find(rule => rule.test.test('.svg'))
      svgRule.exclude = [path.resolve(__dirname, 'assets/svg')]
      // Includes /icons/svg for svg-sprite-loader
      config.module.rules.push({
    
    
        test: /\.svg$/,
        include: [path.resolve(__dirname, 'assets/svg')],
        loader: 'svg-sprite-loader',
        options: {
    
    
          symbolId: 'icon-[name]'
        }
      })
    }
  }

ok, the end of this article

Guess you like

Origin blog.csdn.net/qq_26373925/article/details/108405038