- npm install --save-dev file-loader
- npm install --save-dev css-loader
Remember, loaders are transformations that are applied on the source code of the module. They allow you to pre-process files as you import or load them. Loaders similar to other build tools perform tasks and handle front end build steps. For this gist loaders allow the import of CSS files directly into javascript modules.
Now add to the webpack module.rules property
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
For example, here is a simple site structure and we will import a picture from Portfolio/public/images/hiking.jpg and use it in the Home.js component.
*Portfilio app Components About.js App.js Header.js Home.js Links.js Nav.js Projects.js index.js node_modules public images hiking.jpg package-lock.json .babelrc package.json webpack.config.js
import Hiking from '../../public/images/hiking.jpg';
/* in a div somewhere add Hiking var to <img src={Hiking}...*/
const Home = () => {
return (
<div>
<img className="hiking" src={Hiking} alt={'hiking pic'} />
</div>
When Hiking is imported, that image will be processed and added to the output directory and the Hiking variable will contain the final url of that image after processing. The same is true if using the css-loader and you need a background image in the css file.