2017-12-03 308 views
0

我已經使用收集組件文件與文件index.js出口放置在目錄的圖案,例如:使用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' 

我認爲這應該是可以實現的,但我無法弄清楚這種模式所需的正確語法或修改。任何代碼示例或更好的做法建議,讚賞。提前致謝!

+1

你在使用CRA嗎?你用什麼圖像資源加載?的WebPack? – Li357

+0

好點,我應該宣佈我正在使用webpack 3. –

回答

0

如果您使用的是webpack,請查看require。您可以使用需要導入文件如下面的例子:

樹形目錄

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

圖像/ index.js

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

頁/ home.js

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

我希望我幫你

+0

嘿,這是我正在尋找的語法,謝謝!將圖像聲明爲「const」並需要資產是有意義的。 –