2017-10-04 64 views
0

我正在使用webpack for react.js,但有加載靜態圖像的問題。 在我的反應組件中,我嘗試從例如mainContainer.js文件中加載圖像。我試着用文件加載器,我認爲我把它設置正確,但仍然webpack簡單不能識別圖像文件夾。反應 - 加載靜態圖像

這是一個到Github的內聯鏈接。從我的.js組件

部分在那裏我試圖加載圖像:

<a href="/" className="author"> 
    <span className="name">Jane Doe</span><img src="./images/avatar.jpg" alt="" /> 
</a> 

和的WebPack配置文件的一部分:

module.exports = { 
    entry: './src/scripts/main.js', 
    output: { 
     path: path.resolve(__dirname, 'dist'), 
     filename: 'bundle.js', 
     // publicPath: '/dist' 
    }, 
    module: { 
     rules: [ 
      { 
       test: /\.js$/, 
       use: [ 
        { 
         loader: 'babel-loader', 
         options: { 
          presets: ['es2015'] 
         } 
        } 
       ] 
      }, 
      { 
       test: /\.scss$/, 
       use: extractPlugin.extract({ 
        use: ['css-loader', 'sass-loader'] 
       }) 
      }, 
      { 
       test: /\.html$/, 
       use: ['html-loader'] 
      }, 
      { 
       test: /\.(jpg|png)$/, 
       use: [ 
        { 
         loader: 'file-loader', 
         options: { 
          name: '[name].[ext]', 
          outputPath: 'images/', 
          publicPath: 'images/' 
         } 
        } 
       ] 
      }, 
      { 
       test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/, 
       use: 'url-loader' 
      } 
     ] 
    }, 
    plugins: [ 
     extractPlugin, 
     new HtmlWebpackPlugin({ 
      template: 'src/index.html' 
     }) 
     // new CleanWebpackPlugin(['dist']) 
    ] 
}; 
+0

發佈您的代碼,而不是鏈接的相關部分的GitHub – Micho

+0

請張貼您的代碼 –

+0

@SyedAqeel我編輯了我的帖子 –

回答

1

我這樣做的方式,這是通過使用CopyWebpackPlugin將所有靜態圖像複製到生成文件夾中。

const copy = new CopyWebpackPlugin([ 
    { from: ROOT + '/images', to: 'images' } 
]); 

在您的組件:然後在我的組件,如果他們在根級別存在我可以引用它們

<img src="/images/logo.png" /> 
+0

感謝它的工作原理。 –