我正在使用ReactJS创建一个网站,并使用Webpack对其进行 bundle 。

我的组件之一只是一列包含图像(徽标)的列。现在大约有15张图像将被随机显示,但是这个数目肯定会随着时间而增加。

当然,如果我对所有这些进行硬编码,那将真的很糟糕,例如:

import image01 from './logos/01.png';
import image02 from './logos/02.png';
import image03 from './logos/03.png';
.
.
.

这意味着每次我必须添加新图像时都要更改代码。

我是这样做的:

logos.jsx
import React from 'react';
import './logos.css';

export default class Logos extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      logos: null
    }
  }

  componentWillMount() {
    fetch('/random_logos')
    .then(res => res.json())
    .then(json => {
      this.setState({
        logos: json.logos
      });
    });
  }

  render() {
    return (
      <div className="logos">
        // code to display the logos in a column
      </div>
    );
  }
}

这会从后端获取随机可用的徽标列表,并使其可用于组件。

碰巧我只需执行npm start,我的代码就可以工作,但是当我将所有内容与Webpack bundle 在一起时,Webpack不会将my/application/dir/src/logos/logos下的文件移动到正确的目录(即my/application/dir/resources/images/logos)中,因为它们没有被导入!

有没有一种方法可以告诉Webpack在特定目录下处理文件,而无需在我们的代码中特别要求它们?还是我必须创建一个scritp才能将这些文件复制到生产目录中?

这是我的Webpack配置:

webpack.config.js
var path = require('path');

module.exports = {
    entry: path.resolve(__dirname, 'fe/src/') + '/index.jsx',
    output: {
        path: path.resolve(__dirname, 'public/js'),
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: [ "node_modules" ],
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react','stage-0']
                }
            },
            {
                test: /\.css$/, loader: "style-loader!css-loader"
            },
            {
                test: /\.(jpe?g|png|gif|bmp|svg|ico)$/i,
                use: 'file-loader?name=[name].[ext]&outputPath=resources/images/'
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file-loader?name=resources/fonts/[name].[ext]'
            }
        ]
    }
}

如果我有五个名为01.png02.png03.png04.png05.png的文件,我的后端将返回如下JSON:
{
  "logos": [
    "05.png",
    "03.png",
    "01.png",
    "02.png",
    "04.png"
  ]
}

最佳答案

我建议使用https://github.com/kevlened/copy-webpack-plugin。只需将插件添加到您的webpack配置中,如下所示:

const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  ...,
  plugins: [
    new CopyWebpackPlugin([
        { from: '...', to: '...' }
    ])
  ]
}

然后,只需从正确的文件夹中引用您的徽标即可。

09-04 01:53
查看更多