About the SVG

  • SVG can be read and modified by a wide range of tools (such as vscode)
  • No distortion, zoom in and out the image is very clear
  • An SVG file is pure XML and also a DOM structure
  • Easy to use, the design software can be directly exported

Usage scenarios

Let me start with my usage scenario: this is a React project managed using webPack tools. Now THAT I have downloaded several.svg files locally, I am ready to import and use these SVG files directly in the React project.

If your project isn’t React or doesn’t use WebPack management, this blog post may not exactly solve your problem, but you can take a look at my ideas.

Method of use

1. Configure the rules for processing SVG

You cannot use native SVG files in the React component if you have not configured webPack. If you import SVG files directly, you may encounter the following errors during compilation:

Note the error message in the red box: we need a loader to process SVG files. Here is a very useful loader: file-loader

First, run the following command to install the Loader:

npm install file-loader --save-dev
Copy the code

After the installation is complete, add a processing rule to the webpack.config.js file as follows:

module.exports = {
    // Other configuration rules are omitted
    module: {rules:[
            {
                test: /\.(ttf|eot|svg|woff(2)?) (\? [a-z0-9=&.]+)? $/.loader: "file-loader? name=assets/[name].[ext]"}}};Copy the code

2. Use SVG in the React component

With the processing rules configured, you can now use SVG files directly in the React component in a way that is very similar to images.

import React from 'react'

// Import SVG files
const logoSvg = require("images/logo.svg")

class Login extends React.Component {
    render() {
        return (
            <div className="login-page">{/* use SVG as a normal image */}<img src={logoSvg}></img>   
            </div>); }}export default Login;
Copy the code