hi i override the webpack of the create-react-app, in a separate override-webpack.ts file.
What i do is:
- bundle the js files and copy them into
build/static/js
- bundle the css files and copy them into
build/static/css
- **copy the /assets/img folder and copy them into
build/static/media
**NOT all the images from assets
folder are copied.The ones that are used into react components, are ignored, like so:
<img width="34 src={${url}/img/car.svg} alt="car" />
Context:
So all the js & css files are correctly bundled.
My issue is that the images(png,svg) from the src/assets/img
are copied into build/static/media
, are only the ones that are used into the scss
files, and NOT from whithin my react components, these images are ignored, (as i show above), and that is what i looking for, how to include them also in the build folder
my override-webpack.ts is like this:.
var configurator = {
paths(paths) {
// paths
},
webpack(config, env) {
//if stage, prod, dev
bundleSass()
addMedia()
overrideOutput()
return config;
}
}
module.exports = configurator;
// overrride the publicPath of the bundles, so to have it into index.html
function overrideOutput(config) {
config.output.filename = 'static/js/[name].[hash:8].js';
config.output.chunkFilename = 'static/js/[name].[hash:8].chunk.js';
config.output.publicPath = `http://www.something.com/`; // this is added into index.html
}
// copy images to build/static folder, i was hoping to copy the fonts as well but it does not..
// this functionality ONLY copies the images that are called into the css files,
// it IGNORES the images that used into react components,
// like:
// <img width="34 src={`${url}/img/user.svg`} alt="user" />
function addMedia(config){
const media = {
test: /\.(woff(2)?|ttf|eot|svg|png)(\?v=\d \.\d \.\d )?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'static/media', // by default it creates a media folder
}
}
]
};
config.module.rules.push( media ); // push the rule to the module array
}
// bundle scss files
function bundleSass(config) {
// add rule for the sass-loader, so to bundle the scss files
}
Any suggestions why the images from inside the react components are not copied to the build/static/media
is welcome.
CodePudding user response:
The problem is, that you are not importing the used images in React but just linking to them. Try importing and using image files like so:
import CarImage from '../../img/car.svg';
// further down in the component
<img width="34 src={CarImage} alt="car" />
Now webpack should recognize the imports and write the files.