Dar*_*lie 6 import export image node.js reactjs
我一直在使用一种收集组件文件的模式,以便将index.js
文件放在目录中进行导出,例如:
// index.js file in /components directory
export { Splash } from './Splash'
export { Portfolio } from './Porfolio'
export { Contact } from './Contact'
Run Code Online (Sandbox Code Playgroud)
在Layout.js
(位于根目录中)我可以通过一个调用整齐地导入:
import { Splash, Portfolio, Contact } from '.'
Run Code Online (Sandbox Code Playgroud)
当我跨目录和子目录构建组件时,我经常使用这种模式。
我的具体问题是问是否有任何方法可以将此模式扩展到收集的图像资产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'
Run Code Online (Sandbox Code Playgroud)
我认为这应该是可以实现的,但我无法弄清楚此模式所需的正确语法或修改。任何代码示例或更好的实践建议表示赞赏。提前致谢!
要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 './';
Run Code Online (Sandbox Code Playgroud)
要导出文件:图像、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'
Run Code Online (Sandbox Code Playgroud)
//在Component.js中调用
import { Img01, Img02, Img03 } from '../assets/img'
Run Code Online (Sandbox Code Playgroud)
如果您正在使用 webpack,请查看此require。您可以使用 require 导入文件,如下例所示:
树目录
-images
|_index.js
|_notification.png
|_logo.png
-pages
|-home.js
Run Code Online (Sandbox Code Playgroud)
图片/index.js
export const notification = require('./notification.png')
export const logo = require('./logo.png')
Run Code Online (Sandbox Code Playgroud)
页面/home.js
import { notification } from '../images/'
<img src={notification} />
Run Code Online (Sandbox Code Playgroud)
我希望我对你有帮助
归档时间: |
|
查看次数: |
10457 次 |
最近记录: |