具有语义反馈和webpack的图像组件的路径
问题描述:
我正在构建一个ReactJS应用程序使用webpack。具有语义反馈和webpack的图像组件的路径
这个简单的例子应该呈现<img>
与给定的网址为src
-属性。
如何将图像资源与webpack捆绑在一起并通过合适的加载程序进行处理?我无法弄清楚,为什么图像资源不捆绑。
我不包括产生admin.bundle.js
这样<script src="/admin/dist/admin.bundle.js"></script>
,因为我不谈论督促环境。我只是使用webpack-dev-server --inline --hot
,所以我包括这样的admin.bundle.js
: <script src="http://localhost:8080/admin/dist/admin.bundle.js"></script>
它完全有效。
import React from 'react';
import { Container, Image } from 'semantic-ui-react';
import MainMenu from './menu/components/MainMenu';
const App =() => (
<Container>
<Image src="/res/img/image.png" />
<MainMenu />
</Container>
);
export default App;
我(Symfony和ReactJS)项目的目录结构如下(我中省略不相关的目录/文件澄清):
.
├── README.md
├── app
│ ├── AppCache.php
│ ├── AppKernel.php
│ ├── Resources
│ │ ├── client
│ │ │ └── admin
│ │ │ ├── node_modules
│ │ │ ├── package.json
│ │ │ ├── src
│ │ │ │ ├── App.jsx
│ │ │ │ ├── index.jsx
│ │ │ │ ├── menu
│ │ │ │ └── res
│ │ │ ├── webpack.config.js
│ │ └── views
│ └── config
└── web
├── admin
│ ├── dist
├── app.php
└── app_dev.php
我webpack.config.js是这样:
const path = require('path');
const webpack = require('webpack');
const basePath = path.normalize(__dirname + '/../../../../');
module.exports = {
entry: [
'./src/index.jsx'
],
output: {
filename: 'admin.bundle.js',
publicPath: '/admin/dist/',
path: path.resolve(basePath, 'web', 'admin', 'dist')
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [ 'react-hot-loader', 'babel-loader', 'eslint-loader' ]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.(png|jpg)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 40000 // 40 kB
}
}
]
},
{
test: /\.(eot|woff|woff2|svg|ttf)([\?]?.*)$/,
loader: "file-loader"
}
]
},
resolve: {
modules: [
path.resolve(__dirname, 'src'),
'node_modules'
],
extensions: [ '.js', '.jsx' ]
},
devServer: {
hot: true,
inline: true
}
};
答
为了webpack捆绑您的图像,您需要像导入任何其他资源一样导入它。不知道路径是否正确,因为我不知道您的图像位于何处,但这是一般想法。
import React from 'react';
import { Container, Image } from 'semantic-ui-react';
import MainMenu from './menu/components/MainMenu';
import myImage from '/res/img/image.png';
const App =() => (
<Container>
<Image src={ myImage } />
<MainMenu />
</Container>
);
export default App;
谢谢。这就是诀窍。 我刚刚确信,装载程序也会通过组件的道具扫描参考资源... –
这有点令人困惑,因为它会自动在CSS中使用时拾取URL。 background-image:url(/res/img/image.png) – ryandrewjohnson