【问题标题】:Warning add image via React and Webpack [duplicate]警告通过 React 和 Webpack 添加图像 [重复]
【发布时间】:2018-04-10 17:03:15
【问题描述】:

当我尝试通过 webpack 添加一些图像并做出反应时,图像在浏览器上看起来很好,但我收到了下一个警告:

WARNING in ./index.html
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <!DOCTYPE html>
| <html>
|   <head>
 @ . ^.*$
 @ ./quiz.jsx
 @ ./app.jsx
 @ ./main.jsx  

这是我的反应组件:

import * as React from 'react';

export const Quiz = (props) => {
    const img = './images/williamshakespeare.jpg';
    return (
        <div className='row'>
            <div className='col-md-4'>
                <img src={require(`${img}`)} alt='author' />
            </div>
        </div>
    );
}

如果我直接放:

<img src={require(./images/williamshakespeare.jpg)} alt='author' />

警告没有出现。

已解决: 好吧,我不知道为什么,但为了避免警告,我不得不将 require 从 src 移动到 const img ,例如:

export const Quiz = (props) => {
        const img = require('./images/williamshakespeare.jpg');
        return (
            <div className='row'>
                <div className='col-md-4'>
                    <img src={img} alt='author' />
                </div>
            </div>
        );
    }

【问题讨论】:

    标签: reactjs webpack


    【解决方案1】:

    Dynamically Add Images React Webpack。您需要使用url-loader,这将允许您导入图像

    import williamshakespeare from './images/williamshakespeare.jpg';
    ...
    <img src={require(williamshakespeare)} alt='author' />
    

    【讨论】:

    • 感谢您的回答,在写问题之前,我阅读了该帖子并解决了我的问题,但现在我收到了一个新警告,尽管图像显示正常。
    猜你喜欢
    • 2015-12-13
    • 2018-07-31
    • 2018-04-10
    • 2019-09-26
    • 2017-09-09
    • 2017-06-01
    • 2013-02-23
    • 1970-01-01
    • 2017-01-18
    相关资源
    最近更新 更多