首页 > 解决方案 > 在 webpack 4 中导入图像

问题描述

嗨,我如何在 webpack 4 中导入图像?

这是我的 Webpack 配置。图像加载在静态文件夹中,但名称是神秘的。如果我想导入它并将其注销,则只有带有文件名的字符串。我怎样才能正确使用它?

在此处输入图像描述

在此处输入图像描述

输出图像

这就是我使用它的方式

import img  from "../../../../assets/hallo.png"

<img style = "height: 100px;width: 100px" src="${img}" />

Webpack 配置

const path = require('path')
const BrowserSyncPlugin = require("browser-sync-webpack-plugin")
var webpack = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports  ={
  entry: './src/js/index.js',
  output: {
    path: path.resolve(__dirname, 'static'),
    filename: 'monitor-bundle.js'

  },
  devtool: 'source-map',
  mode: 'development',

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract(
          {
            fallback: 'style-loader',
            use: ['css-loader']
          })
      },
      {
        test: /\.(jpg|png)$/,
        use: {
          loader: "file-loader",
        }
      },
    ]
  },
  watch: true,
  plugins: [
    new BrowserSyncPlugin({
      watchOptions: {
        poll: true
      },
        host: "localhost",
        port: "1337",
        proxy: "http://localhost:80/",
        files: ["./static/monitor-bundle.js"],
        open: true,
        reloadDelay: 0,
        reloadDebounce: 0,
        browser: ["chromium", "google chrome"]
    }),
    new ExtractTextPlugin({filename: 'monitor-style.css'})
],
};

标签: javascriptjquerywebpack

解决方案


您只是在这里传递一个空字符串作为源。

<img style = "height: 100px;width: 100px" src="${img}" />

如果你想使用这个 ${},你需要使用模板字符串

<img style = "height: 100px;width: 100px" src=`${img}` />

在这种情况下,您可以这样做

 <img style = "height: 100px;width: 100px" src={img} />

推荐阅读