Import multiple similar svg sources in create-reac

2019-07-14 20:50发布

问题:

I'm going to import a bunch of SVG illustrations into my project as inline SVG components using the new feature of create-react-app @2.0.0.

Here is my svg-import.js:

import React from 'react';

import { ReactComponent as StartLogo } from '../images/start/logo.svg';
import { ReactComponent as StartTitle } from '../images/start/title.svg';
...

import { ReactComponent as IntroAvatar } from '../images/intro/avatar.svg';
import { ReactComponent as IntroDialog } from '../images/intro/dialog.svg';
...

const svgIllustrations = {
  "start": {
    "logo": <StartLogo className="svg svg-start-logo"/>,
    "title": <StartTitle className="svg svg-start-title"/>,
    ...
  },
  "intro": {
    "avatar": <IntroAvatar className="svg svg-intro-avatar"/>,
    "dialog": <IntroDialog className="svg svg-intro-dialog"/>,
    ...
  }
}

export default svgIllustrations;

When I want to use them:

import svgIllustrations from '../svg-import.js';

...
render() {
  return (
    {svgIllustrations.start["logo"]}
  )
}

The code works.

However, since there're lots of SVG files to be imported and all of them are named and structured under a certain rule, I'm wondering if there's a better way to do something like this.

回答1:

If it were me personally, I probably would do away with the intermediary svgIllustrations and just import the svgs directly from the images directory wherever I want to use them. Your object basically replicates the file structure, so I'm not seeing what pulling all the svg's in a single place is really buying you. Importing them directly also might help when it comes to code splitting; in the current setup you propose, you have to load all of the svg's in order to display one of them. If you import them directly from the images directory, you could split out a page and you would only be loading the svg's for that page. This may not be a concern depending on the size of your app and the number of svg's you are loading.

Having said that, if you still really want this object representation for all your svg's, the only thing I would say you might want to do is generate your svgIllustrations from your images directory. Since your object structure is basically a replica of your file structure, it would likely be pretty easy to do so and maybe save you a little bit of time.