webpack导入图片出现问题

按照文档抄的webpack.config.js配置,可是在浏览器打开html发现css可以被import进来,图片则没被加载

const webpack = require('webpack');
const path = require('path');
module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            }, {
                test: /\.(png|svg|jpg|gif)$/,
                use: ['file-loader']
            }
        ]
    }
};

目录结构

clipboard.png

index.js

import './style.css';
import ys from './ys.jpg';
var element = document.createElement('div');
element.innerHTML = "导入图片和css";
element.classList.add('hello');
var myIcon = new Image();
myIcon.src = ys;
element.appendChild(myIcon);
document.body.appendChild(element)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>导入图片</title>
</head>
<body>
    <script src="./dist/bundle.js"></script>
</body>
</html>
阅读 3.1k
1 个回答

路径问题

  1. webpack 默认 publicPath='' 所以 myIcon.src = ys; 编译后类似于 myIcon.src = publicPath + '[hash].jpg';
  2. output.path 是编译后文件存放路径(即 dist 目录),因此编译后的图片([hash].jpg)是存放在这个目录下
  3. 你直接打开 index.html 文件,相当于根目录是 index.html 所在目录,而这个目录是没有图片文件的所以报 404 错误

有两种解决方式:

  1. 设置 publicPath 为 dist (不推荐这样)

    module.exports = {
      output: {
        publicPath: 'dist/'
      }
    }
  2. webpack-dev-server 相应的 html 改为 <script src="bundle.js"></script>,然后开启 server,访问 http://localhost:port/

PS: 注意发布的时候尽量设 publicPath 为 CDN 地址 或 网站静态文件所在地址。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题