Loading local images with webpack

旧城冷巷雨未停 提交于 2019-12-11 08:44:07

问题


Hi I am trying to load local images with webpack, it compiles successfully however I get the following error (and no image)

GET http://192.168.1.196:3000/b09d0fa90cacadcad6ce1679aea3d2ee.png 404 (Not Found)

Here is my webpack.config.js file:

    const path = require('path')

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'public/scripts'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env']
                }
            }
            },
            { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }

        ]
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'public'),
        publicPath: '/scripts/'
    },
    devtool: 'source-map'
}

Here is how I am importing the image

import goku from '../public/images/goku.png'

I am trying also with require in the img directly with the same result.

<img src =${require('../public/images/goku.png')}>
<img src =${goku}> 

回答1:


Your problem is actually that you missed a publicPath on output:

output: {
        path: path.resolve(__dirname, 'public/scripts'),
        filename: 'bundle.js',
        publicPath: '/scripts/'
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'public'),
        publicPath: '/scripts/'
    },

The property publicPath on output has to match the publicPath on devServer.



来源:https://stackoverflow.com/questions/52481728/loading-local-images-with-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!