Unable to load background image from Css file Webpack5 - css

I'm trying to put an image as background in a div but it doesn't recognize it because webpack changes the path to http://localhost:8080/gaia.png instead of http://localhost:8080/assets/images/gaia.png
The image is displayed correctly inside an tag but it doesn't load if I want to use it from the Css file.
I'm sure the problem is the file path but I don't know how to fix it.
index.js
import './assets/style/style.css'
import './assets/images/gaia.png'
import './assets/fonts/CascadiaCode.ttf'
const fun = () => {
console.log('hey')
}
fun();
webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require('path');
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src', 'index.html')
})
],
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
generator: {
filename: '[name][ext][query]',
outputPath: 'assets/images/',
},
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
generator: {
filename: '[name][ext][query]',
outputPath: 'assets/fonts/',
},
},
],
},
};
style.css
.container {
width: 300px;
height: 300px;
background-image: url("../images/gaia.png");
background-size: auto;
}

delete outputpath and set it up as :
generator: {
filename: 'assets/images/[hash][ext][query]'
}
}

I fixed the problem by installing a specific loader for Html images
npm install --save-dev html-loader image-webpack-loader
I followed this tutorial: Optimizing Static HTML And Images With Webpack
Here is my webpackconfig.js file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
static: './dist',
},
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src', 'index.html'),
}),
],
module: {
rules: [
{
test: /\.css/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.html$/i,
use: 'html-loader',
},
{
test: /\.(png|jpg)$/i,
type: 'asset/resource',
generator: {
filename: 'images/[name]-[hash][ext]',
},
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
generator: {
filename: 'fonts/[name]-[hash][ext]',
},
},
],
},
};
I also created a Webpack Template that you can use with the default configuration on my GitHub:
Webpack Template Repo

Related

SVG in CSS is interpreted via webpack with "module.exports = 'data:...'" instead of valid svg

I use webpack to compile scss. The scss also contains url to svg files, which I need to process and link to css with correct url.
However, instead of a valid svg, I get a file (eebc108eb2b00c4b2784.svg) with the following content:
module.exports = "data:image/svg+xml,%3csvg width='30px' height='30px' xmlns=...'
which is linked to css like:
background-image: url(../eebc108eb2b00c4b2784.svg);
That is what i want basically, but svg obviously dont show. This SVG is not used anywhere in JS only in CSS.
My webpack config looks like this:
const webpack = require("webpack");
const path = require("path");
const AssetsPlugin = require("assets-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
let config = {
watch: true,
entry: {
appAdmHomepage: "./_devapp/AppAdmHomepage.js",
cssStyle: "../css/primary/style.scss",
cssAdm: "../css/primary/administrace.scss",
cssPrint: "../css/primary/print.scss",
cssObjProces: "../css/primary/objednavkovy_proces.scss",
cssDesign: "../css/primary/design.scss",
},
output: {
filename: "[name].bundle.js",
chunkFilename: "[name].[contenthash].js",
path: path.resolve(__dirname, "assets", "bundle")
},
resolve: {
extensions: [".js", ".jsx", ".json", ".ts", ".tsx", ".css", ".scss"]
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: path.resolve(__dirname, "node_modules"),
use: {
loader: "babel-loader",
options: {
presets: [
"#babel/preset-env",
["#babel/preset-react",{
"runtime": "automatic"
}]
],
plugins : [
["#babel/plugin-proposal-decorators", { version: "legacy" }],
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-private-methods",
]
}
},
}, {
test: /\.svg$/,
use: [
{
loader: "svg-url-loader",
options: {
name: "./image/[name]--.[ext]"
},
},
],
}, {
test: /\.scss$/,
include: [
path.resolve(__dirname, "../css/primary/")
],
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
url: true,
import: true
}
},
"sass-loader"
]
}, {
test: /\.css$/, //pro datepicker
use: [
"style-loader",
{
loader: "css-loader",
options: {
url: true
}
}
]
}
],
},
plugins: [
new webpack.DefinePlugin({
"__DEV__" : JSON.stringify(true),
"__API_HOST__" : JSON.stringify("http://127.0.0.1:8080/www/eshop/www"),
"__PATH_HOST__" : JSON.stringify("/www/eshop/www"),
}),
new AssetsPlugin({
prettyPrint: true,
removeFullPathAutoPrefix: true,
fullPath: true
}),
new MiniCssExtractPlugin({
filename: "./css/[name].min.css"
}),
new CleanWebpackPlugin()
]
};
module.exports = config;
Is there a way to link correct form of SVG or am i making a mistake somewhere? Thanks for help

Node modules don't apply css

I'm new to React development and I try to use webpack to set up my project. Unfortunately, I have a problem with my configuration: with it, components from node_modules don't apply styles no matter if I try to build the application or to start it with webpack-dev-server.
My webpack.config.js:
const path = require('path')
const HtmlPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.jsx',
output: {
filename: 'main.js',
path: path.join(__dirname, 'dist')
},
resolve: {
extensions: ['.js', '.jsx']
},
plugins: [
new HtmlPlugin({
template: './src/index.html'
})
],
module: {
rules: [
{
test: /\.jsx?/i,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/i,
use: 'css-loader'
},
{
test: /\.(png|jpe?g|ttf|svg)/i,
use: 'file-loader'
},
]
},
devServer: {
port: 9000,
contentBase: path.join(__dirname, 'dist')
}
}
.babelrc:
{
"presets": ["#babel/preset-react"]
}
UPD: I didn't mean the styles I wrote, but the styles of the components themselves. For example, Button component of the primereact renders like the default html button.

Module parse failed: Unexpected character '#' (1:0) You may need an appropriate loader to handle this file type

I'm having some issues. I keep getting this error
Module parse failed: Unexpected character '#' (1:0) You may need an
appropriate loader to handle this file type, currently, no loaders are
configured to process this file. See
https://webpack.js.org/concepts#loaders
#import url("https://cloud.typography.com/7374818/6819812/css/fonts.css");
I've tried some of the suggested solutions I've found online and none seems to work.
This is what my Webpack config looks like
const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const devMode = process.env.NODE_ENV !== 'production';
module.exports = {
entry: {
main: path.resolve(__dirname, './src/App.tsx'),
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'public'),
sourceMapFilename: "[name].js.map"
},
externals: {
'react': 'React',
'react-dom': 'ReactDOM',
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,
include: [
path.resolve(__dirname, './src'),
],
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react', '#babel/preset-typescript'],
},
},
{
test: /\.(scss|css)$/,
include: path.resolve(__dirname, './src'),
use: [
MiniCssExtractPlugin.loader,
'style-loader',
'css-loader',
{
loader: "postcss-loader",
options: {
plugins: () => [
require("autoprefixer")()
],
},
},
'sass-loader',
],
},
{
test: /\.(png|woff|woff2|eot|ttf|otf|svg)$/,
loader: 'url-loader',
options: {
limit: 100000,
}
},
],
},
resolve: {
extensions: ['.js', '.jsx', 'json', 'ts', 'tsx', '.scss'],
alias: {
src: path.resolve(__dirname, './src/'),
},
},
devServer: {
historyApiFallback: true,
contentBase: './public',
port: 3030,
open: true,
compress: true,
hot: true,
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
plugins: [
new MiniCssExtractPlugin({
filename: devMode ? '[name].css' : '[name].[hash].css',
chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
}),
new CleanWebpackPlugin(),
new webpack.HotModuleReplacementPlugin(),
],
};
The component looks like this. uilib is a local dependency I'm linking using yarn link
import React from 'react';
import ReactDOM from 'react-dom';
import { Header, Footer } from 'uilib';
import 'uilib/index.css';
export const App: React.FC<{}> = () => (
<>
<Header/>
<div>Hello in oct</div>
<Footer/>
</>
);
ReactDOM.render(
<App />,
document.getElementById('root'),
);
The uilib/index.css looks like this
#import url("https://cloud.typography.com/7374818/6819812/css/fonts.css");
.header {
height: 70px;
}
I feel that ulib folder is perhaps not inside src directory.
Can you try changing your webpack loader config for scss|css to be like so:
{
test: /\.(scss|css)$/,
include: path.resolve(__dirname) // <---- leave it __dirname or remove the prop completely
....
....
}
I am hoping this will let webpack look at project's root which can help it parse the file accordingly.
Also, unless ulib is in node_modules, you can exclude it from loader with exclude: 'node_modules'

webpack build css img url cant get reletive path

I am using webpack with reactJs.
I am trying, with css, to set background-image.
when I build my project I always get the same path for img url no matter what I try.
'http://localhost:8080/images/img1.png '
instead of - 'http://localhost:8080/dist/images/img1.png'
Folder structure:
src/
App/
app.jsx
app.html
app.css
public/
images/
img1.png
img2.png
index.jsx
index.html
dist/
images/
img1.png
img2.png
bundle.js
main.bundle.css
index.html
webpack.config.js
webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
// HTML plugin options
let htmlOptions = {
template: './src/index.html',
filename: 'index.html',
inject: 'body',
}
module.exports = {
entry: './src/index.jsx',
output: {
path: path.resolve('dist'),
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-3']
},
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.jpe?g$|\.ico$|\.gif$|\.png$|\.svg$|\.wav$|\.mp3$/,
loader: 'file-loader',
options: {
outputPath: 'img/',
name: '[name].[ext]',
publicPath: '/dist'
}
},
{
test: /\.(ttf|eot|woff|woff2)$/,
use: {
loader: "file-loader",
options: {
name: "fonts/[name].[ext]",
},
},
},
]
},
devtool: 'source-map',
plugins: [
new HtmlWebpackPlugin(htmlOptions),
new CleanWebpackPlugin(['dist']),
new CopyWebpackPlugin([{ from: __dirname + '/src/public' }])
],
devServer: {
historyApiFallback: true
}
}
app.css
body{
background-image: url('/images/loginImageBg.png');
}
**I have tried **
plugins : new ExtractTextPlugin - for some resone Conflicts with cleanWebpackPlugin.
url-loader
query: {outputPath: './data/'}
publicPath , outputPath
nothing I do seems to work
Please help !

sass-loader with extract-text-plugin not outputting file

I have configured my webpack.config.js as following:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
// plugins
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : null,
entry: "./js/init.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties',],
}
},
{
test: /\.json$/,
include: /node_modules/,
loader: 'json-loader'
},
{
test: /\.scss$/,
loaders: ExtractTextPlugin.extract(
'style',
'css!sass'
)
}
]
},
output: {
path: __dirname + "/src/",
filename: "app.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
new ExtractTextPlugin('default.css'),
],
devServer: {
port: 3000,
historyApiFallback: {
index: 'index.html'
}
},
sassLoader: {
includePaths: [path.resolve(__dirname, "src/css/sass")]
},
resolve: {
alias: {
'#': path.resolve(__dirname, 'src/js'),
'!': path.resolve(__dirname, 'src/css/sass')
}
},
};
And this is my file structure:
- src
-- css
--- sass
---- default.scss
-- js
-- index.html
Yet I don't see my default.css file exported anywhere when I run webpack dev server. Does it not work with webpack dev server?
Edit: Simply running webpack does not work either.

Resources