Search code examples
javascriptreactjswebpacklocalhostwebpack-2

How to get static image paths working in Webpack 2 / React App on localhost?


Expected

Images and CSS path load up fine locally with no errors

Results

404 errors on style and images

enter image description here

My styles work fine, yet there is a missing error, also the app cannot find the static/imgs folder

enter image description here

My folder structure

enter image description here

Login component

The image path:

render() {
    return (
        <div className="app-bg">
            <section id="auth-section">
                <header>
                    <img src="static/imgs/logo.png"/>
                    <h1>Login to the Manage app</h1>
                </header>

Webpack Config

const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");

module.exports = {
  context: path.resolve(__dirname, "src"),
  entry: [
    "./index.js"
  ],
  output: {
    path: dist,
    filename: "manage2.bundle.js",
    publicPath: "/"
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallbackLoader: "style-loader",
          loader: ["css-loader", "sass-loader"],
          publicPath: dist
        })
      }
    ]
  },
  devServer: {
    hot: false,
    quiet: true,
    publicPath: "",
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    stats: "errors-only",
    open: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      // title: "Manage 2.0",
      // hash: true,
      template: "index.html"
    }),
    new ExtractTextPlugin({
      filename: "manage2.css",
      disable: false,
      allChunks: true
    }),
    new CopyWebpackPlugin([{ from: "static" }])
  ]
};

src/index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import css from './manage2.scss'
const element = document.getElementById('manage2');
ReactDOM.render(<App />, element);

I've tried changing the publicPath: "/" to "", ./ to no avail...


Solution

  • Ah I needed to change the publicPath to below:

    output: {
      path: dist,
      filename: "manage2.bundle.js",
      publicPath: '/static/',
    },