最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get Webpack Dev Server to display images stored locally? - Stack Overflow

programmeradmin0浏览0评论

I migrated a project I have been working on to Webpack 2 and this has been kind of a headache. But I have gotten my project to preview using Webpack dev server, except it won't show my image. All I get is this error in the browser console GET http://localhost:8080/logo.jpg 404 (Not Found)

and in MacOS Console:

   ERROR in ./js/components/Global/Menu.jsx Module not found: Error: Can't resolve 'logo.jpg' in '/Users/user1/Documents/AAA/app/js/components/Global'

This is my Webpack configuration:

    const path = require('path');

    module.exports = {
      context: __dirname + "/app",

      entry: {
        app: "./js/app.js",
        javascript: "./js/app.js",
        html: "./index.html",
      },

      output: {
        //output.path: "[name].js",
        path: __dirname + "/dist",
        filename: "[name].js"
      },

      resolve: {
        alias: { 'react/lib/ReactMount': 'react-dom/lib/ReactMount' },
        extensions: [ '*', '.js', '.jsx', '.json'],
        modules:[__dirname, './app/js', 'node_modules'],
      },

      module: {
        rules: [
          {
            test: /\.jsx?$/,
            include: [
              path.resolve(__dirname, "app")
            ],
            loaders: ["babel-loader"],
          },
          {
            test: /\.html$/,
            loader: ["file-loader?name=[name].[ext]"],
          },
          {
            test: /\.(jpe?g|png|gif|svg)$/i,
            include : path.join(__dirname, 'app'),
            loader  : 'url-loader?limit=30000&name=images/[name].[ext]'
          }
        ],
      },
    }

The migration has broken multiple images but heres one and I can use is it as a base to fix the others:

import React, { Component } from 'react';
import { Link } from 'react-router';

import Logo from "logo.jpg";

export default class Menu extends Component {
  render() {
    return (
      <div className='Menu' id='Menu'>
        <img src={Logo}></img>
        <Link to='/'>Home</Link>  <Link to='/about'>Clothing</Link>  <Link to='/Cart'>Cart</Link>
        <hr />
      </div>
    );
  }
}

Should I use url('logo.jpg')? Why is the dev server not finding the images and displaying them?

EDIT

Tried with:

let img = new Image();
img.src = require('logo.jpg');

and <img src={img.src}>, but it gives me the same error.

I migrated a project I have been working on to Webpack 2 and this has been kind of a headache. But I have gotten my project to preview using Webpack dev server, except it won't show my image. All I get is this error in the browser console GET http://localhost:8080/logo.jpg 404 (Not Found)

and in MacOS Console:

   ERROR in ./js/components/Global/Menu.jsx Module not found: Error: Can't resolve 'logo.jpg' in '/Users/user1/Documents/AAA/app/js/components/Global'

This is my Webpack configuration:

    const path = require('path');

    module.exports = {
      context: __dirname + "/app",

      entry: {
        app: "./js/app.js",
        javascript: "./js/app.js",
        html: "./index.html",
      },

      output: {
        //output.path: "[name].js",
        path: __dirname + "/dist",
        filename: "[name].js"
      },

      resolve: {
        alias: { 'react/lib/ReactMount': 'react-dom/lib/ReactMount' },
        extensions: [ '*', '.js', '.jsx', '.json'],
        modules:[__dirname, './app/js', 'node_modules'],
      },

      module: {
        rules: [
          {
            test: /\.jsx?$/,
            include: [
              path.resolve(__dirname, "app")
            ],
            loaders: ["babel-loader"],
          },
          {
            test: /\.html$/,
            loader: ["file-loader?name=[name].[ext]"],
          },
          {
            test: /\.(jpe?g|png|gif|svg)$/i,
            include : path.join(__dirname, 'app'),
            loader  : 'url-loader?limit=30000&name=images/[name].[ext]'
          }
        ],
      },
    }

The migration has broken multiple images but heres one and I can use is it as a base to fix the others:

import React, { Component } from 'react';
import { Link } from 'react-router';

import Logo from "logo.jpg";

export default class Menu extends Component {
  render() {
    return (
      <div className='Menu' id='Menu'>
        <img src={Logo}></img>
        <Link to='/'>Home</Link>  <Link to='/about'>Clothing</Link>  <Link to='/Cart'>Cart</Link>
        <hr />
      </div>
    );
  }
}

Should I use url('logo.jpg')? Why is the dev server not finding the images and displaying them?

EDIT

Tried with:

let img = new Image();
img.src = require('logo.jpg');

and <img src={img.src}>, but it gives me the same error.

Share Improve this question edited May 5, 2017 at 2:33 feners asked May 2, 2017 at 23:43 fenersfeners 6756 gold badges19 silver badges50 bronze badges 11
  • /Users/user1/Documents/AAA/app/js/components/Global is that where your images live ? – pizzarob Commented May 4, 2017 at 23:56
  • @realseanp yes..I dont know why it's not finding them.. – feners Commented May 5, 2017 at 0:04
  • Out of curiosity, why are you not doing <img src="./logo.jpg">? – hazardous Commented May 5, 2017 at 6:26
  • Also, your import paths in the components should be relative to the location of the images. As your images are in Global, the relative paths in your components should point to the images accordingly. Unless you setup an alias to make it easier. – hazardous Commented May 5, 2017 at 6:28
  • @hazardous using <img src=.?logo.jpg> was giving me the same error so looking for answers I found that React Dev Server can't read file like this? This just has me completely confused at this point.. – feners Commented May 5, 2017 at 14:12
 |  Show 6 more comments

5 Answers 5

Reset to default 4 +50

Your webpack configuration doesn't declare explicitly output.publicPath setting. A basic configuration might be like:

  output: {
    publicPath: '/',
    path: __dirname + "/dist",
    filename: "[name].js"
  },

Further consideration: since your logo.jpg lives in the same directory as your component, why not importing it with a ./ relative path?

import Logo from "./logo.jpg";

You should review this guide: https://webpack.js.org/guides/migrating/

you use old format config for webpack1, config for webpack2 below;

module: {
rules: [
  {
    test: /\.jsx?$/,
    include: [
      path.resolve(__dirname, "app")
    ],
    use: ["babel-loader"],
  },
  {
    test: /\.html$/,
    use: [{
        loader: 'file-loader',
        options: {
           name: '[name].[ext]'
        }
    }],
  },
  {
    test: /\.(jpe?g|png|gif|svg)$/i,
    include : path.join(__dirname, 'app'),
    use: [{
        loader: 'url-loader',
        options: {
           limit: 30000,
           name: '[name].[ext]'
        }
    }]
  }
],
  },

I think I know the issue. You are not specifying the correct path for the image when importing. Try adding an alias for the image folder

resolve: {
    alias: { 
      'react/lib/ReactMount': 'react-dom/lib/ReactMount',
      images: '/Users/user1/Documents/AAA/app/js/components/Global', // absolute path to images folder
    },
    extensions: [ '*', '.js', '.jsx', '.json'],
    modules:[__dirname, './app/js', 'node_modules'],
  },

Then import your images like this:

import Logo from 'images/logo.jpg';

specifying absolute publicPath worked for me. Reference

 {
    test: /\.(png|jpg)$/,
    include: path.join(__dirname, '/app'),
    loader: 'url-loader',
    query: {
      outputPath: path.join(__dirname, '/app/dist'),,
      publicPath: 'http://localhost:8080/',
      emitFile: true,
    },
  },

You actually just have to add that image inside the public folder and you can directly use it as <img src="logo.png" />

发布评论

评论列表(0)

  1. 暂无评论