使用 index.js 在 React 中导入多个图像资源

Use index.js to import multiple image assets in React

我一直在使用一种模式来收集用于导出的组件文件,其中 index.js 文件放置在目录中,例如:

// index.js file in /components directory
export { Splash } from './Splash'
export { Portfolio } from './Porfolio'
export { Contact } from './Contact'

Layout.js(位于根目录)我可以一键导入:

import { Splash, Portfolio, Contact } from '.'

我经常使用这种模式,因为我跨目录和子目录构建组件。

我的具体问题是问是否有任何方法可以将此模式扩展到 src/assets/img 中收集的图像资产?我可以在我的图像目录中放置一个 index.js 文件并能够将图像组调用到一个组件吗?

//index.js in /src/assets/img directory
export { Img01 } from './img-01.png'
export { Img02 } from './img-02.jpg'
export { Img03 } from './img-03.svg'

//Call in Component.js
import { Img01, Img02, Img03 } from '../assets/img'

我认为这应该是可以实现的,但我无法弄清楚此模式所需的正确语法或修改。任何代码示例或更好实践的建议都值得赞赏。提前致谢!

如果您正在使用 webpack,请查看此 require。您可以使用 require 导入文件,如下例所示:

树目录

-images 
  |_index.js
  |_notification.png
  |_logo.png
-pages
  |-home.js

images/index.js

export const notification = require('./notification.png')
export const logo = require('./logo.png')

pages/home.js

import { notification } from '../images/'
<img src={notification} />

希望对你有所帮助

export默认组件这样做:

export { default as Splash } from './Splash'
export { default as Portfolio } from './Porfolio'
export { default as Contact } from './Contact'

// you dont need to include the 'index' on the route, just do './' if you 
// are in the same directory, but your export file must be named index.js
import { Splash, Portfolio, Contact } from './';

要导出文件:图像、css、.svg 等,只需包含文件扩展名:

export { default as Img01 } from './img-01.png'
export { default as Img02 } from './img-02.jpg'
export { default as Img03 } from './img-03.svg'

//调用Component.js

import { Img01, Img02, Img03 } from '../assets/img'