首页 > 解决方案 > 为什么我的 img 中的 require() 在与 Bulma 一起使用时不能正常工作?

问题描述

我正在尝试require()在我的一个Bulma组件中使用动态显示图像。还因为我使用的是 webpack(我没有create-react-app用来启动我的项目),但由于某种原因,在控制台中,我收到一条错误消息:

ERROR in ./src/images/myImage.png 1:0 Module parse failed: Unexpected character '�' (1:0) You may need an appropriate loader to handle this file type.

错误中的文件路径不正确,这对我来说很奇怪。它的阅读方式是否与导致此错误的预期不同?

我试过<img src={myImage} alt="image"/>(没有require()),但它仍然不起作用。

我做错了什么,我该如何解决?

我已将其标记为{/* Here's the problem */}指向导致错误的行。

这是我的代码:

import React from 'react';
import myImage from '../../images/myImage.png';

const Tiles = () => {
    return(
        <div className="tile">
            <div className="tile is-vertical is-8">
                <div className="tile">
                    <div className="tile is-parent is-vertical">
                        <article className="tile is-child notification">
                            <p className="title">Vertical...</p>
                            <p className="subtitle">Top tile</p>
                        </article>
                        <article className="tile is-child notification">
                            <p className="title">...tiles</p>
                            <p className="subtitle">Bottom tile</p>
                        </article>
                    </div>
                    <div className="tile is-parent">
                        <article className="tile is-child notification">
                            <p className="title">Middle tile</p>
                            <p className="subtitle">With an image</p>
                            <figure className="image is-4by3">
                                <img src="https://bulma.io/images/placeholders/640x480.png"/>
                            </figure>
                        </article>
                    </div>
                </div>
                <div className="tile">
                    <article className="tile is-child notification">
                        <p className="title">Wide tile</p>
                        <p className="subtitle">Aligned with the right tile</p>
                        <div className="content">
                            {/* Here's the problem */}
                            <img src={require(myImage)} alt="image"/>
                        </div>
                    </article>
                </div>
            </div>
            <div className="tile is-parent">
                <article className="tile is-child notification">
                    <div className="content">
                        <p className="title">Tall tile</p>
                        <p className="subtitle">With even more content</p>
                        <div className="content">
                        </div>
                    </div>
                </article>
            </div>
        </div>
    );
}

export default Tiles;

这是我的 webpack 文件:

const path = require("path");
const webpack = require("webpack");

const imageRule = {
    test: /\.(ico|gif|jpe?g|png)(\?.+)?$/i,
    use: [
        {
            loader: 'url-loader',  // defaults to file-loader (with options) when image size > options.limit
            options: {
                limit: 8192,
                name: 'assets/[sha512:hash].[ext]'
            }
        },
        'image-webpack-loader'
    ]
};


module.exports = {
    entry: "./src/index.js",
    mode: "development",
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules|bower_components)/,
                loader: "babel-loader",
                options: { presets: ["@babel/env"] }
            },
            {
                test: /\.css$/,
                use: ["style-loader", "css-loader"]
            },
            imageRule
        ]
    },
    resolve: { extensions: ["*", ".js", ".jsx"] },
    output: {
        path: path.resolve(__dirname, "dist/"),
        publicPath: "/dist/",
        filename: "bundle.js"
    },
    devServer: {
        contentBase: path.join(__dirname, "public/"),
        port: 3000,
        publicPath: "http://localhost:3000/dist/",
        hotOnly: true
    },
    plugins: [new webpack.HotModuleReplacementPlugin()]
};

标签: javascriptreactjsdebuggingbulma

解决方案


您需要在 Webpack 配置中设置图像规则。这是我使用的一个:

const imageRule = {
  test: /\.(ico|gif|jpe?g|png)(\?.+)?$/i,
  use: [
    {
      loader: 'url-loader',  // defaults to file-loader (with options) when image size > options.limit
      options: {
        limit: 8192,
        name: 'assets/[sha512:hash].[ext]'
      }
    },
    'image-webpack-loader'
  ]
};

此规则将内联小于 8KB 的图像。你需要image-webpack-loader并且url-loaderdevDependencies你的package.json和规则module.rules中你的 Webpack 配置的部分,即

...
module: {
  rules: [ ..., imageRule, ... ]
},
...

作为参考,这里是完整的 Webpack 配置,其中包含上面的代码片段。


推荐阅读