N
N
Nikita Shchypylov2018-03-07 13:37:40
React
Nikita Shchypylov, 2018-03-07 13:37:40

How to properly load static files (images, docs) in React/Webpack?

Hello everyone
I can't upload a picture to the project, it gives either "not found" or "unknown character"
webpack.config.js:

const path = require("path");
const webpack = require("webpack");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");

const BUILD_DIR = path.resolve(__dirname, "./dist");

module.exports = {
  context: path.join(__dirname, "/"),
  entry: ["babel-polyfill", "./src/index.js"],
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name].js"
  },
  devServer: {
    contentBase: "./dist",
    // outputPath: BUILD_DIR,
    // hot: true,
    historyApiFallback: true
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader: "style-loader"
          },
          {
            loader: "css-loader"
          },
          {
            loader: "sass-loader"
          }
        ]
      },
      {
        test: /\.css/,
        use: ["style-loader", "css-loader"]
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader"
          }
        ]
      },
      { test: /\.(jpe?g|gif|jpg|png|svg|woff|ttf|wav|mp3)$/, loader: "file", include: '/*/**' }
    ]
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: "./public/index.html",
      filename: "./index.html"
    }),
    new CopyWebpackPlugin([{ from: "./public/img/*", to: "./img" }], {})
  ]
};

Attempts:
1) It gave unknown charaster, supposedly I need a loader, although I have it
const noImage = require('./img/no_image.jpeg');
2)
The same
<img src='./img/no_image.jpeg' alt=""/>
How to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-03-07
@Nikulio

For the first option: try file-loader(not just file).
For the second option: the picture must be taken from the public directory.

output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/' // название директории
  },

In the second case, the image will not get into webpack, but will be given as is.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question