简体   繁体   中英

react components as destructed export

I'm building my app using create-react-app. I have folder structure like src/images/icons and in the icons folder I have index.js:

import Logo from "./my-logo.svg";

export {
  Logo
}

I did that because I can use any icons anywhere like

import { Logo } from '../images/icon'

otherwise I would have to do

import Logo from '../images/icons/my-logo.sv'

Usually a page won't have 1 or 2 icons, it can be more, I don't want to have super long import. But it doesn't really solve the problem.

The problem is that the index.js within src/images/icon still grow. Every time I add a new icon on my icon folder I have to alter the index.js. Any better solution for this?

You can directly re-export the default export using named export format, since the default export's name is literally default :

export {default as Logo} from "./my-logo.svg";

That replaces the four lines (ignoring the blank one) you currently have in index.js , and avoids having to list Logo twice (which is a maintenance hazard).


Note : This is true for true JavaScript modules, so I'd expect it to work even with a bundler like Webpack or Rollup (which I'm guessing you're using, since you're importing an SVG, which isn't JavaScript functionality but is the kind of thing bundlers often add).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM