I have a common use case to load a spinner in the component. This is my folder structure.
src
/components
/table
-Table.js
-Spinner.js
I import spinner like this
const spinner = require('./spinner.gif');
When I console log spinner I got this
And call that in the component like this
<img src={spinner} alt='Data is loading...' />
But gif image is not loading. Instead I am getting the alt text.
How do I fix this with React?
My answer follows the documentation on webpack
In your folder add a package for image loader
npm install --save-dev file-loader
Then change your webpack.config.js or any other named config file as below.
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
],
},
// Added below -----------
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
],
},
// Added above ---------------
],
},
};
Then you can import images as usual by doing
import image from './image.gif';
Or
const image = require('./image.gif')
Related
I am trying to load a local image in a simple React application with Webpack. I load the image as:
const DogImage = require('../../public/dog.jpg');
const Image = () => {
...
<img src={DogImage} width="100px"/>
}
My webpack config includes the following:
output: {
filename: 'widget.js',
path: path.resolve(bundleOutputDir),
publicPath: '/public/'
},
devServer: {
contentBase: bundleOutputDir,
publicPath: '/public/'
},
...
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
When I build the app, I get the image file named 8ce03579ff1756938e787945c032a0a3.jpg in my dist folder and when I console.log the image I get:
It shows up on the screen with the HTML missing file icon. The image is definitely in the correct path because I can't build if the path doesn't match the image.
Please let me know if you have any ideas or if I can provide more info! Thanks
I am using webpack and react js.
I am getting this error when i try to import image or font file inside my scss file.
I have tried many solutions but none of them solved my problem,
webpack.common.js
enter image description here
const path = require("path");
var HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: {
main: "./src/index.js",
vendor: "./src/vendor.js"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(ttf|svg|png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "imgs"
}
}
}
]
}
};
Here is another webpack.dev.js
module.exports = merge(common, {
mode: "development",
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist")
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/template.html"
})
],
module: {
rules: [
{
test: /\.scss$/,
use: [
"style-loader", //3. Inject styles into DOM
"css-loader", //2. Turns css into commonjs
"sass-loader" //1. Turns sass into css
]
}
]
}
});
ERROR in ./src/assets/index.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/lib/loader.js!./src/assets/index.scss)
Module not found: Error: Can't resolve '../../../src/assets/fonts/icomoon.ttf' in 'C:\Users\jamal\Documents\webpack-demo-app\src\assets'
# ./src/index.js
# multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js
You need to remember that the import actually takes "place" from the root index.scss file (the one that loads all the other partials). So the path you are using to fetch the asset is not accurate.
You need to use ./fonts/icomoon.ttf instead of ../fonts/icomoon.ttf
your file structure:
assets/
------/fonts
------/images
------/sass
------/---/partial1.scss // while the reference to the image is here
------/index.scss // the actual root of the reference call is here
I am building a simple React app from scratch using Webpack.
I was finally able to run the dev server and when I tried to apply some styles via CSS, the files wouldn't load and I assume my Webpack 4 configuration is not right.
Here is the code:
webpack.config.js
// const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require('path');
module.exports = {
mode: 'development',
entry: ['./src/index.js'],
resolve: {
extensions: [".js", ".jsx"]
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist',
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 8080
},
module: {
rules: [
{
test: /\.js|.jsx$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: ["react"]
}
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(png|jpg)$/,
loader: 'url-loader'
}
]
},
};
My project structure is like this, I will include only src because it lives in the root:
**src**
|_assets
|_componentns
|_styles
|_App.css
|_index.css
App.jsx
index.js
index.html
I would like to be able to add multiple css files for each component I have and apply them, and to be able to style the index the index.html.
Thank you very much for your help.
Your webpack configuration looks fine.
make sure you import the required css files in your components.
import "./App.css";
class App extends Component {
render() {
return (
<div>
<Child />
</div>
);
}
}
All you have to do is import the CSS files when needed as you would a JavaScript module. So if you want to have a style sheet for your whole application, you can import a global stylesheet in your index.js.
import './styles/index.css';
and you can do the same for each component with specific styles
import './styles/App.css'
in which case you might want to setup CSS modules to avoid overlapping class names.
Ok, rookie mistake here, the way I ahve set up webpack is I have to build it first and then run the dev server, no the other way around.
All answers above are valid and helpful, I just forgot to run build after changes.
My team moved all the images of company website into a CDN. (https://cdn.irobo.co.kr/images)
However, I'd like to use those images without changing current code base, which has a lot of: (reactjs code)
<image src={require('img/common/logo.jpg')} />
here's the webpack config for the website:
{
module: {
loaders:[{
test: /\.(png|jpg)$/,
loader: 'file-loader?name=[name].[ext]',
}],
}
...
resolve: {
alias: {
img: path.join(srcPath, 'app/img'),
}
}
}
Here's what I tried:
...
resolve: {
alias: {
img: 'https://cdn.irobo.co.kr/images',
}
}
}
Bundling assets from external urls with Webpack
The url-loader plugin for webpack gives you the ability to take use assets from external url by encoding them in base64.
The url loader works like the file loader, but can return a Data Url
if the file is smaller than a byte limit.
The limit can be specified with a query parameter. (Defaults to no
limit)
Remember to install the url-loader plugin as a project dependency.
npm install --save-dev url-loader
Configure the url-loader plugin
Here is a sample webpack config to set up the url-loader plugin.
webpack.config.js
module.exports = {
entry: './main.js',
output: {
path: './build', // This is where the images and js will go
publicPath: 'http://mycdn.com/', // used to generate URLs to e.g. images
filename: 'bundle.js'
},
module: {
loaders: [
// use ! to chain loaders
{ test: /\.less$/, loader: 'style-loader!css-loader!less-loader' },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
// inline base64 URLs for <=8k images, direct URLs for the rest
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
]
}
};
Import the assets in your app
app.jsx
import image from '../build/image.jpg';
<img src={image} />
I am able to build the example app of app of AG-Grid. It's running smoothly and is styled nicely.
Then I would like to move it to my app but it seems that the styles are not applied. I put all the example files from https://github.com/ceolter/ag-grid-react-example/tree/master/src to a new folder in my project thus making a component that I use in my app:
import React from 'react'
import AgGrid from './AgGrid/myApp.jsx';
// Pages
export default class PatPorts extends React.Component {
render() {
return (
<div>
<h2>Ports</h2>
<div>Some home page content</div>
<AgGrid/>
</div>
)
}
}
My webpack.config is the following:
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, '../public/js');
var APP_DIR = path.resolve(__dirname, 'app');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.css$/,
loader: "style!css"
},
{
test: /\.js$|\.jsx$/,
loader: 'babel-loader',
include: APP_DIR, // Where to look for *.js and *.jsx
query: {
presets: ['react', 'es2015']
}
}
]
},
plugins: [
new webpack.NoErrorsPlugin() // do not automatically reload if there are errors
],
resolve: {
alias: {
"ag-grid-root" : __dirname + "/node_modules/ag-grid"
}
}
};
module.exports = config;
I am new to react so I may be missing something elementary... Any ideas? I can find myApp.css in the generated bundle. How to make it work?
I was missing style sheets from the lib:
import 'ag-grid-root/dist/styles/ag-grid.css';
import 'ag-grid-root/dist/styles/theme-fresh.css';