本文介绍了使用webpack加载本地图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用webpack加载本地图像,它可以成功编译,但是出现以下错误(并且没有图像)

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(未找到)

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

这是我的webpack.config.js文件:

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'
}

这是我导入图像的方式

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

我也在尝试在img中直接使用require来获得相同的结果.

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

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

推荐答案

您的问题实际上是您在输出中错过了publicPath

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/'
    },

输出上的publicPath属性必须与devServer上的publicPath相匹配.

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

这篇关于使用webpack加载本地图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 10:08