警告通过React和Webpack添加图像

时间:2017-10-29 17:16:23

标签: reactjs webpack

当我尝试通过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' />

警告没有出现。

解决: 好吧,我不知道为什么要避免警告我必须将需求从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>
        );
    }

1 个答案:

答案 0 :(得分:0)

Dynamically Add Images React Webpack。您需要使用url-loader来导入图片

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