Mevia
Mevia

Reputation: 1564

react production build, assets not loading

I am experiencing annoying problem, when i run my react app in development environment it all works ok, but when i try to build to production, all the links are wrong.

assume this tree:

Now in some_component.jsx i am referencing svg file in this way:

src="/public/svg/some_img.svg"

however after building to production this path is untouched and therefore cannot access file anymore, as there i would need it to be changed to this:

src="svg/some_img.svg"

i was playing in the webpack config file, i thought that maybe by setting:

publicPath: "/"

to:

publicPath: "/public/"

would resolve the problem but the only thing it did was error during application start:

CANNOT GET/

my webpack config:

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

const htmlPlugin = new HtmlWebPackPlugin({
  template: "./public/index.html",
  filename: "./index.html"
});

module.exports = {
  output: {
    filename: "main.[hash:8].js",
    publicPath: "/"
  },
  module: {
    rules: [
      {
        test: /\.jsx$/,
        exclude: /node_modules/,
        loader: "babel-loader?presets[]=react"
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.(sass|scss)$/,
        use: ["style-loader", "css-loader", "sass-loader", "postcss-loader"]
      },
      {
        test: /\.svg$/,
        loader: "svg-sprite-loader"
      }
    ]
  },
  plugins: [htmlPlugin],
  devServer: {
    historyApiFallback: {
      rewrites: [{ from: /^\/$/, to: "/index.html" }]
    }
  },
  resolve: {
    extensions: [".js", ".jsx", ".json"]
  }
};

How does one resolve this problem, so for both dev and production paths are unified?

Upvotes: 0

Views: 5717

Answers (2)

Mevia
Mevia

Reputation: 1564

this is the solve for the question, config required for to specify path:

module: {
    ...
    rules: [
        {
            test: /\.(png|jpg|gif|svg|ico)$/,
            loader: 'file-loader',
            query:{
                outputPath: './img/',
                name: '[name].[ext]?[hash]'
            }
        }
        ...
    ]
}

Upvotes: 0

twils0
twils0

Reputation: 2633

How about importing the svg and then referencing the imported variable:

import someImg from "../../public/svg/some_img.svg"

src={someImg}

Upvotes: 2

Related Questions