带有 semantic-ui-react 和 webpack 的图像组件的路径

Path for Image Component with semantic-ui-react and webpack

我正在使用 webpack.ReactJS 构建应用程序。

这个简单的示例应该将给定的 url 呈现为 <img> 作为 src 属性。

如何将图像资源与 webpack 捆绑在一起,并通过适当的加载程序对其进行处理?我想不通,为什么图像资源没有被捆绑。

我不包括像这样 <script src="/admin/dist/admin.bundle.js"></script> 生成的 admin.bundle.js,因为我 不是 谈论 prod 环境。我只是使用 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)项目的目录结构如下(我省略了不相关的 directories/files 以澄清):

.
├── 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;