简体   繁体   English

从公共文件夹反应导入图像

[英]React import images from public folder

I'm trying to get static images fro my public directory but is not being found.我正在尝试从我的公共目录中获取 static 图像,但没有找到。 I'm not using CRA, so maybe is some configuration with Webpack that I'm missing.我没有使用 CRA,所以可能是我缺少 Webpack 的一些配置。 Using file-loader module and importing the image works on Dev Mode, but doesn't work in for my production server specification使用文件加载器模块并导入图像适用于开发模式,但不适用于我的生产服务器规范

My Project structure:我的项目结构:

\public
   \static
      \images
         image.png
\src
   \component
      component.js
...
package.json
webpack.common.js
webpack.dev.js
webpack.prod.js

On component.js, I want to get image.jpg on static/images folder like this:在 component.js 上,我想在 static/images 文件夹中获取 image.jpg,如下所示:

  <img src='/static/images/image.png'></img>

But I'm getting a 404 not found.但我得到一个 404 未找到。

My webpack.commom.js:我的 webpack.commom.js:

const CleanWebPackPlugin = require('clean-webpack-plugin')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const path = require('path')

module.exports = {
    entry: {
        main: './src/index.js'
    },
    output: {
        filename: '[name].[hash].js',
        path: path.resolve('./dist'),
        publicPath: "/"
    },
    module:{
        rules:[
            {
                test: /\.js$/,
                exclude: ['/node_modules'],
                use: [{ loader: 'babel-loader'}],
            },
            {
                test: /\.s?(a|c)ss$/,
                use: [{
                    loader: 'style-loader'
                }, {
                    loader: 'css-loader'
                },{
                    loader: 'sass-loader'
                }]
            },
            {
                test: /\.(png|jpe?g|gif)$/,
                use: [
                  {
                    loader: 'file-loader',
                    options: {},
                  },
                ],
              },

        ]
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: 'index.html'
        }),
        new CleanWebPackPlugin(),
    ],
}

And the Dev version:和开发版本:

module.exports = merge(common, {
    mode: 'development',
    devServer: {
        host: 'localhost',
        port: 3000,
        open: true,
        historyApiFallback: true,
        publicPath: "/",
    }
})

Thank you in advance.先感谢您。

You are using file-loader as webpack plugin, which does not work in the way of "just mirroring the directory structure of public to dist".您正在使用file-loader作为 webpack 插件,它不能以“仅将public的目录结构镜像到 dist”的方式工作。 You can find the documentation for that plugin here: https://webpack.js.org/loaders/file-loader/您可以在此处找到该插件的文档: https://webpack.js.org/loaders/file-loader/

Basically, what the plugin does is, if you import an image file (actually programatically importing it, not just using a string reference to its path), the file is copied to your dist directory, potentially renamed and than in your compiled source code the proper file name is inserted.基本上,插件的作用是,如果您导入图像文件(实际上是以编程方式导入它,而不仅仅是使用对其路径的字符串引用),该文件将被复制到您的 dist 目录,可能重命名,而不是在您编译的源代码中插入正确的文件名。

So in your case, if you want to solve your problem using file-loader , you would reference the image file like所以在你的情况下,如果你想使用file-loader解决你的问题,你会引用图像文件,如

// Relative path to image file from js file
import imageFile from './assets/image.png';

// ...
const component = props => <img src={imageFile}></img>;

If you want to use the approach of actually just mirroring a public -directory to the dist directory, you need to use an additional webpack-plugin for that (eg https://stackoverflow.com/a/33374807/2692307 )如果您想使用实际上只是将public目录镜像到 dist 目录的方法,则需要为此使用额外的 webpack-plugin(例如https://stackoverflow.com/a/33374807/2692307

By the way, I assume it works in dev-mode because you are setting '/' as public path, so the development server just serves everything in the root directory as well.顺便说一句,我假设它在开发模式下工作,因为您将“/”设置为公共路径,因此开发服务器也只提供根目录中的所有内容。 That is something different than copying the files to dist however as you are trying to achieve.这与将文件复制到 dist 是不同的,但是当您尝试实现时。

I assume you want to display such image more than once.我假设您想多次显示此类图像。 In that case, is annoying to keep writing something like '%PUBLIC_URL%/img/static/images/image.png' or {process.env.PUBLIC_URL + '/img/static/images/image.png'} two, three or more times within your jsx code.在这种情况下,继续写 '%PUBLIC_URL%/img/static/images/image.png' 或 {process.env.PUBLIC_URL + '/img/static/images/image.png'} 二、三或更多次在您的 jsx 代码中。 Basically, without a plugin is imposible to import images from the public folder if your app is rooted in the src folder.基本上,如果您的应用程序植根于 src 文件夹,则没有插件是不可能从公共文件夹导入图像的。 However I did find a solution for me and was quite simple in fact.但是,我确实为我找到了解决方案,实际上非常简单。 It was something like this:是这样的:

import React from 'react'

var path = process.env.PUBLIC_URL;
var image = "/img/static/images/image.png";

and then, within jsx code:然后,在 jsx 代码中:

<img src={path + image}/>

it worked for me, hope this is helpful for anyone: :D它对我有用,希望这对任何人都有帮助::D

Not sure if this help but I'm will give it a try不确定这是否有帮助,但我会尝试一下

Try to add public path to your dist folder also something like this尝试将公共路径添加到您的 dist 文件夹也是这样的

output: {
        path: path.resolve(__dirname, "/dist"),
        filename: "[name].js",
        publicPath: "/dist/"
    },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM