May Webpack handles all images in a directory without requiring them?
I am creating a site with ReactJS and using Webpack to bundle it.
One of my components is just a column of images (logos). There will now be about 15 images displayed, but this number will undoubtedly increase over time.
Of course it would be really bad if I hd to hardcode all of them, like this:
import image01 from './logos/01.png';
import image02 from './logos/02.png';
import image03 from './logos/03.png';
.
.
.
This would mean changing the code every time I had to add a new image.
I am doing this:
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>
);
}
}
It selects a random list of logos available from the indoor unit and makes it available to the component.
It happens that my code works when I just do npm start
, but when I compile everything with Webpack, my pod files are my/application/dir/src/logos/logos
not pushed into the correct directory by Webpack, which it would be my/application/dir/resources/images/logos
because they werenβt imported!
Is there a way to tell Webpack to process files in a specific directory without requiring them in our code? Or would I have to create a scritp to copy these files to my production directory?
This is my Webpack config:
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]'
}
]
}
}
If I had five files with the name of 01.png
, 02.png
, 03.png
, 04.png
and 05.png
, my back-end would return JSON like this:
{
"logos": [
"05.png",
"03.png",
"01.png",
"02.png",
"04.png"
]
}
source to share
I suggest using https://github.com/kevlened/copy-webpack-plugin . Just add the plugin to your webpack config, for example:
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
...,
plugins: [
new CopyWebpackPlugin([
{ from: '...', to: '...' }
])
]
}
Then just list your logos from the correct folder.
source to share