导入图像React / Webpack4为路径生成index:letter对象

时间:2018-12-27 20:30:08

标签: reactjs webpack webpack-4

非常感谢您提供任何指导!当我在我的React组件中导入图像时,它返回一个带有key:value index:[url-letter] 的对象,并以 default:“ full-url-path” 结尾>:

enter image description here

因此,我需要调用 thumbnail.default 而不是仅 thumbnail 来访问图像网址:

class Product extends PureComponent {
    state = {
        thumbnail: "",
    }

    componentDidMount() {
        import(`../assets/images/${this.props.product.thumbnail}`)
            .then(thumbnail =>
                this.setState({
                    thumbnail
                })
            ).catch(err => {
                console.log('Error importing thumbnail: ' + err)
            })
    }

    render(){
        const { thumbnail } = this.state;
        const { product } = this.props;

        thumbnail && console.log("THUMBNAIL: ", thumbnail);

        const categoryName = product.catName;

        const thumbnailImage = thumbnail && 
            <div 
                className="product-image"
                style={{ backgroundImage: 'url(' + thumbnail.default + ')' }}
            />

        return (
            <div>
                <div className={this.addContainerClass(product.catName)}>
                    {thumbnailImage}
                </div>
            </div>
        )
    }
}

enter image description here

为什么它会返回这样的对象?为什么不直接使用网址?

这是我的webpack:

const entry = [
	'webpack-dev-server/client?http://localhost:8888',
	'webpack/hot/only-dev-server',
	'./app.js'
]

const output = {
	path: path.join(__dirname, 'dist'),
	publicPath: '/dist',
	filename: 'bundle.min.js'
}

const plugins = [
	new webpack.HotModuleReplacementPlugin(),
	new webpack.NamedModulesPlugin()
]

const config = {
	context: path.join(__dirname, 'src'),
	mode: 'development',
	entry: entry,
	output: output,
	module: {
		rules: [
			{
				test: /\.(js|jsx)$/,
				exclude: /node_modules/,
				include: path.join(__dirname, 'src'),
				use: {
					loader: "babel-loader"
				}
			},
			{
				test: /\.(png|jpg|gif)$/,
				use: {
					loader: 'file-loader',
					options: {
						name: '/[path][name].[ext]'
					}
				}
			},
			{
				test: /\.(sass|scss)$/,
				use: [
					'style-loader',
					'css-loader',
					'sass-loader'
				]
			}
		]
	},
	plugins: plugins
}

0 个答案:

没有答案