javascriptreactjswebpackpublic-folders

Webpack react. Configure a folder with pictures


Please help configure file-loader so that in a project with such a structure

I could take the image from the public folder in a similar way:

<img src={"/images/globalx_logo.svg"} className="globalx-logo"/>

In an attempt to do something, I wrote this webpack.config.js:

var path = require('path')

module.exports = {
   entry: "./src/index.js",
   output: {
      path: path.resolve(__dirname, './output'),
      publicPath: '/output/',
      filename: 'bundle.js'
   },
   devServer: {
      historyApiFallback: true,
   },
   module: {
      rules: [
         {
            test: /\.m?js$/,
            exclude: /(node_modules|bower_components)/,
            loader: "babel-loader",
            options: {
               presets: ["@babel/preset-env", "@babel/preset-react"]
            }
         },
         {
            test: /\.s[ac]ss$/i,
            use: [
               'style-loader',
               'css-loader',
               'sass-loader'
            ]
         },
         {
            test: /\.(jpg|png|gif|svg)$/,
            loader: 'file-loader',
            options: {
                name: '[name].[ext]',
                publicPath: './public/',
                outputPath: './output/public/'
            }
         }
      ]
   }
}


Solution

  • you can use a loader like this

     {
            test: /\.(jpg|png|gif|svg)$/,
            use: [
              {
                loader: 'url-loader',
                options: {
                  limit: 1000000,
                  fallback: 'file-loader',
                  name: 'images/[name].[hash].[ext]',
                }
              }
            ]
          }
    

    and using import

    import logo from '/images/globalx_logo.svg'
    
     <img src={logo} className="globalx-logo"/>