[英]React import images from public folder
我正在嘗試從我的公共目錄中獲取 static 圖像,但沒有找到。 我沒有使用 CRA,所以可能是我缺少 Webpack 的一些配置。 使用文件加載器模塊並導入圖像適用於開發模式,但不適用於我的生產服務器規范
我的項目結構:
\public
\static
\images
image.png
\src
\component
component.js
...
package.json
webpack.common.js
webpack.dev.js
webpack.prod.js
在 component.js 上,我想在 static/images 文件夾中獲取 image.jpg,如下所示:
<img src='/static/images/image.png'></img>
但我得到一個 404 未找到。
我的 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(),
],
}
和開發版本:
module.exports = merge(common, {
mode: 'development',
devServer: {
host: 'localhost',
port: 3000,
open: true,
historyApiFallback: true,
publicPath: "/",
}
})
先感謝您。
您正在使用file-loader
作為 webpack 插件,它不能以“僅將public
的目錄結構鏡像到 dist”的方式工作。 您可以在此處找到該插件的文檔: https://webpack.js.org/loaders/file-loader/
基本上,插件的作用是,如果您導入圖像文件(實際上是以編程方式導入它,而不僅僅是使用對其路徑的字符串引用),該文件將被復制到您的 dist 目錄,可能重命名,而不是在您編譯的源代碼中插入正確的文件名。
所以在你的情況下,如果你想使用file-loader
解決你的問題,你會引用圖像文件,如
// Relative path to image file from js file
import imageFile from './assets/image.png';
// ...
const component = props => <img src={imageFile}></img>;
如果您想使用實際上只是將public
目錄鏡像到 dist 目錄的方法,則需要為此使用額外的 webpack-plugin(例如https://stackoverflow.com/a/33374807/2692307 )
順便說一句,我假設它在開發模式下工作,因為您將“/”設置為公共路徑,因此開發服務器也只提供根目錄中的所有內容。 這與將文件復制到 dist 是不同的,但是當您嘗試實現時。
我假設您想多次顯示此類圖像。 在這種情況下,繼續寫 '%PUBLIC_URL%/img/static/images/image.png' 或 {process.env.PUBLIC_URL + '/img/static/images/image.png'} 二、三或更多次在您的 jsx 代碼中。 基本上,如果您的應用程序植根於 src 文件夾,則沒有插件是不可能從公共文件夾導入圖像的。 但是,我確實為我找到了解決方案,實際上非常簡單。 是這樣的:
import React from 'react'
var path = process.env.PUBLIC_URL;
var image = "/img/static/images/image.png";
然后,在 jsx 代碼中:
<img src={path + image}/>
它對我有用,希望這對任何人都有幫助::D
不確定這是否有幫助,但我會嘗試一下
嘗試將公共路徑添加到您的 dist 文件夾也是這樣的
output: {
path: path.resolve(__dirname, "/dist"),
filename: "[name].js",
publicPath: "/dist/"
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.