Webp images doesn't render correct - javascript

I have the problem with webpack build webp images. There is SSR react project.
Example of react code:
import slotroulette from './slotroulette.png';
import slotrouletteWebp from './slotroulette.webp';
...
return (
...
<picture>
<source srcSet={slotrouletteWebp} type="image/webp" />
<img
css={{ width: '200px' }}
src={slotroulette}
alt="slot-roulette"
/>
</picture>
...
)
);
};
Example webpack config file:
{
test: /\.(jpe?g|gif|svg|ico|png)$/,
use: [
{
loader: 'file-loader',
options: {
hash: 'sha512',
digest: 'hex',
publicPath: `${CDN_HOST}/pub/`,
outputPath: 'pub/',
name: '[hash].[ext]',
},
},
{
loader: 'image-webpack-loader',
query: {
mozjpeg: {
progressive: true,
},
gifsicle: {
interlaced: false,
},
svgo: {
plugins: [
{
removeViewBox: false,
},
],
},
webp: {
quality: 80,
},
},
},
],
},
In this case i have next error:
ERROR in .../slotroulette.webp
Module parse failed: Unexpected character '' (1:6)
You may need an appropriate loader to handle this file type.
In case I add 'webp' to the 'test'( test: /.(jpe?g|gif|svg|ico|png|webp)$/,) I will get next problem webpack convert webp to png that can't be opened.

This is how I formatted my jsx.
JSX
<picture>
<source srcSet={`${baseUrl.public}img/rsgis-logo.webp`} type="image/webp" />
<source srcSet={`${baseUrl.public}img/rsgis-logo.png`} type="image/png" />
<img src={`${baseUrl.public}img/rsgis-logo.png`} className="rsgis-logo" alt="RS&GIS Logo" />
</picture>
Webpack
I did my webpack a little different. The webp-loader worked well for me except for the fact that it did not transfer the png to the output directory.
With the webp-loader:
loaders: [
{
test: /\.(jpe?g|png)$/i,
loaders: [
'file-loader',
'webp-loader?{quality: 80}'
]
}
]
The webp-loader will convert the images into the webp format. Then place the images in the output/img directory (I didn't specify the output location above as I dont have the code on my person right now)
Then to get the pngs to the output directory, I used the webpack plugin CopyWebpackPlugin. This takes a directory and places it in the output directory.
plugins: [
...,
new CopyWebpackPlugin([
{ from: "./src/images/png", to: "./img" }
]),
...
],
After I did this implementation, I decided to do the reverse.
I did not like the web-loader. I ended up converting my images via CLI using the webp tool and used the CopyWebpackPlugin to move the webp files to the output directory. I then had webpack process my images normally using the file-loader
{
test: /\.(svg|gif|jpe?g|png)$/i,
use: [{
loader: "file-loader",
options: {
name: "/img/[name].[ext]"
}
}]
},
plugins: [
...,
new CopyWebpackPlugin([
{ from: "./src/images/webp", to: "./img" }
]),
...
],
Hopefully this helps a little!

Related

Webpack is not displaying my img but only alt attribute text

as a recruitment task I have to copy layout using HTML/CSS and Vanilla JS. I've got a starter pack as a webpack bundle and according to recruiter documentation i have to just install all dependencies using npm install. After creating some layout in css i had to use img tag and here my problem start. First I had error that I'm missing img-loader, so I installed it. Now i can't see image but only alt attribute text.
this is my webpack.config.js for file-loader and img-loader:
{
test: /\.(jp?g|png|gif|svg)$/i,
use: [
{
loader: "file-loader",
options: {
name: "img/[name].[ext]",
},
},
{
loader: "img-loader",
options: {
enabled: isProduction,
gifscale: {
interlaced: false,
},
mozjpeg: {
progressive: true,
arithmetic: false,
},
optipng: false,
pngquant: {
floyd: 0.5,
speed: 2,
},
svgo: {
plugins: [{ removeTitle: true }, { covertPathData: false }],
},
},
},
],
},
here is file structure: file structure
I tried installing all dependencies step by step, changing config and I searched internet across. Unfortunately i couldn't find any solution.

Support for the experimental syntax 'jsx' isn't currently enabled in Next - next.config.js doesn't work well

So I've got a next app (based on React Native Web) with package.json in several locations as well as tsconfig.json in several places.
I am trying to solve an error I am getting:
Support for the experimental syntax 'jsx' isn't currently enabled (21:5):
19 | const GeneralStatusBarColor = ({ backgroundColor, height, ...props }) => {
20 | return (
> 21 | <SafeAreaView style={{ height: height, backgroundColor: backgroundColor }}>
| ^
22 | <StatusBar
23 | {...props}
24 | backgroundColor={backgroundColor}
But in my next folder, I have a .babelrc:
{
"presets": [
"next/babel",
["babel-preset-expo", { "jsxRuntime": "automatic" }]
],
"plugins": [
["#babel/plugin-proposal-class-properties", { "loose": true }],
["#babel/plugin-proposal-private-methods", { "loose": true }],
["#babel/plugin-proposal-private-property-in-object", { "loose": true }],
"react-native-reanimated/plugin",
[
"module-resolver",
{
"root": "../../packages",
"alias": {
"app": "../../packages/app",
"components": "../../packages/app/components",
"config": "../../packages/app/config",
"controllers": "../../packages/app/controllers",
"pages": "../../packages/app/pages",
"features": "../../packages/app/features",
"reducers": "../../packages/app/redux",
"resources": "../../packages/app/resources",
"revenuecat": "../../packages/app/revenuecat",
"routing": "../../packages/app/routing",
"utils": "../../packages/app/utils",
"interfaces": "../../packages/app/interfaces",
"root": "./"
}
}
]
]
}
This works perfectly fine in another similarly structured app of mine.
But here, I need to have a next.config.js, and I think that's messing up other parts of my app.
Here's what the webpack part of my next.config.js looks like:
config.module.rules.push({
test: /.(js|ts|tsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: [
'next/babel',
['babel-preset-expo', { jsxRuntime: 'automatic' }],
'#babel/react',
],
plugins: [
[
'module-resolver',
{
root: '../../packages',
alias: {
app: '../../packages/app',
components: '../../packages/app/components',
config: '../../packages/app/config',
controllers: '../../packages/app/controllers',
pages: '../../packages/app/pages',
features: '../../packages/app/features',
reducers: '../../packages/app/redux',
resources: '../../packages/app/resources',
revenuecat: '../../packages/app/revenuecat',
routing: '../../packages/app/routing',
utils: '../../packages/app/utils',
interfaces: '../../packages/app/interfaces',
},
},
],
],
},
});
This works to get rid of the error, but seems a bunch extra on top of the .babelrc elsewhere?
However, when I add this code, I get the following error:
ReferenceError: __DEV__ is not defined
The fix for this... remove .babelrc.
Which if I do so, causes this error (likely due to SWC):
error - ../../node_modules/react-native-web/src/modules/normalizeColor/index.js
Error:
x Unexpected token `:`. Expected this, import, async, function, [ for array literal, { for object literal, # for decorator, function, class, null, true, false, number, bigint, string, regexp, `
| for template literal, (, or an identifier
,----
13 | const normalizeColor = (color?: number | string, opacity?: number = 1): void | string => {
But I am also trying to solve that in my next.config.js with this:
config.resolve.alias = {
...(config.resolve.alias || {}),
'react-native$': 'react-native-web',
'#expo/vector-icons': 'react-native-vector-icons',
};
So I am just totally lost - I have a site with a similar config, but for some reason every time I am trying to get this site to work, there's some other error that's causing the whole app to not work, and there seems to be no consistency. I have been trying to fight this collection of errors for four days now.

Unable to configure svgo-loader (webpack)

I'm using svgo-loader to optimize the svg images and its using the default configuration for this. I want to add some custom configuration like I dont want to remove the viewBox from svg as it makes defining the dimensions of svg really hard.
I found the following solutions from internet... but none of them are working, and I always get the viewBox removed from svg.
{
loader: 'svgo-loader',
options: {
plugins: [{
removeViewBox: false
}]
}
}
{
loader: 'svgo-loader',
options: {
externalConfig: "svgo-config.yml"
}
}
{
loader: 'svgo-loader',
options: {
configFile: './svgo.config.js'
}
}
Content of config.yml file
plugins:
- removeTitle: false
- remoViewBox: false
Content of svgo.config.js
const { extendDefaultPlugins } = require('svgo');
module.exports = {
plugins: extendDefaultPlugins([
{
name: 'removeTitle',
active: false
},
{
name: 'removeViewBox',
active: false
},
])
};
For the configFile solution, I feel like it's just not picking the given file, because if I will provide the wrong file location (or some file location that doesnt exists) it works exactly same as the default case (my expectation was to have an error smething like ...wrong file supplied).
Using svgo-loader v3.0.0 (with svgo v2.4.0 or newer):
create svgo.config.js in root project folder with following content:
module.exports = {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false,
},
},
},
],
};
in webpack.config.js
{
test: /\.svg$/i,
use: [
{
loader: 'file-loader',
},
{
loader: 'svgo-loader',
},
]
},
There is no need to pass any options for the svgo-loader in the webpack config. Just passing the default config under the root directory with the required options for fine-tuning the loader worked for me.
Make sure its named svgo.config.js as this is this file that will be picked by the svgo for loading in options...much like how we pass config files for other things like prettier, ts, and so on.
webpack.config.js
{
test: /\.svg$/i,
use: [
{
loader: 'file-loader',
},
{
loader: 'svgo-loader',
},
]
},
And this is my svgo.config.js, since I just need to preserve the viewBox attribute on my SVG I have added that...you can use this complete list for your reference.
const { extendDefaultPlugins } = require('svgo');
module.exports = {
plugins: extendDefaultPlugins([
{
name: 'removeViewBox',
active: false
},
])
};
Thanks for the help #trySound!

VueJS loading SVG file depending on variable in for loop using v-html giving [object Module] instead

I'm trying to load SVGs saved in separate files depending on the content in a loop. When the page loads, I see this:
Hey, Here's my code:
<div
v-for="(rec, index) in stats"
:key="index"
>
<div class="iconForeground align-self-center" v-html="require(`../../../assets/svg/dashboard/attributes/${rec.icon}.svg`)">
</div>
</div>
Here's the data function, I've omitted the whole thing for brevity:
data() {
return {
stats: [{name: "Leadership", percent: "75", top: "5", icon: "leadership"},
{name: "Innovation", percent: "25", icon: "genius-ideas"}] as Array<Record<string, string>>
}
}
How can I accomplish this?
EDIT
Here's my vue.config.js:
const path = require("path");
module.exports = {
pluginOptions: {
'style-resources-loader': {
preProcessor: 'scss',
patterns: [
"./src/styles/global.scss"
]
},
configureWebpack: {
module: {
rules: [{
test: /\.svg$/,
loader: 'vue-svg-loader'
}]
}
}
}
}
EDIT 2 It seems even after installing url-loader and following the advice, I still cannot load the image, here's my updated vue.config.js:
const path = require("path");
module.exports = {
pluginOptions: {
'style-resources-loader': {
preProcessor: 'scss',
patterns: [
"./src/styles/global.scss"
]
},
configureWebpack: {
module: {
rules: [
{
test: /\.svg$/,
loader: 'vue-svg-loader'
},
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
esModule: false,
},
},
],
}]
}
}
}
}
and my html:
<div class="d-flex flex-column justify-content-center" :style="{marginRight: '24px'}">
<div class="purpleDot"></div>
<div class="iconForeground align-self-center">
<img :src="require(`../../../assets/svg/dashboard/attributes/${rec.icon}.svg`)" />
</div>
</div>
The answer is to use dynamic components such as this
<template>
div
v-for="(m, i) in modules"
:key="i">
<component :is="m.image"></component>
</div>
</template>
import PraiseIcon from "#/assets/svg/navigation-bar/Praise-Icon.svg";
components: {
'Praise-Icon': PraiseIcon
},
data() {
return {
modules: [
{
name: "Praise",
image: "Praise-Icon",
}
] as Array<Record<string, string>>
}
}
remove your svg loader
{
test: /\.svg$/,
loader: 'vue-svg-loader'
},
add svg to your url-loader
test: /\.(png|jpg|gif|svg)$/i,
use: [
{
loader: 'url-loader',
options: {
esModule: false,
},
},
],
}
this normally because your webpack loader settings
try set the esModule option in url-loader to false.
this should fix your issue.
you don't need to follow content below.
and another issue, even if you fixed your loader, you still can't load it.
for the image you should use img tag to load it.
<img :src=`require(...)`/>
v-html will only loads it's path string.

Not able to add favicon in gatsby config file

Even after adding favicon to gatsby hello world starter project in gatsby config file, its not working.
I tried googling and searched in stackoverflow for similar question, How do i add favicon gatsby-config.js?. But that doesn't help or i maybe wrong somewhere.
Please correct me!!
GATSBY CONFIG.JS
/**
* Configure your Gatsby site with this file.
*
* See: https://www.gatsbyjs.org/docs/gatsby-config/
*/
module.exports = {
/* Your site config here */
siteMetadata: {
title: "xxxxxxx",
author: "Subin",
},
plugins: [
"gatsby-plugin-react-helmet",
{
resolve: "gatsby-source-contentful",
options: {
spaceId: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
},
},
"gatsby-plugin-sass",
// this plugin will pull all the files in our project system
{
resolve: "gatsby-source-filesystem",
options: {
name: "src",
path: `${__dirname}/src/`,
icon: `../src/images/favicon-32x32.png`,
},
},
"gatsby-plugin-sharp",
// REMARK plugin needed to extract the markdown files and parses
{
resolve: "gatsby-transformer-remark",
options: {
plugins: [
"gatsby-remark-relative-images",
{
resolve: "gatsby-remark-images",
options: {
maxWidth: 750,
linkImagesOriginal: false,
},
},
],
},
},
],
}
PROJECT DIRECTORY IMAGE
Image : Tree hierarchy of my project structure
To display your favicon, you need to have the gatsby-plugin-manifest installed, it doesn't come with the hello world starter.
npm install --save gatsby-plugin-manifest
And here is your gatsby-config.js with some default settings to this plugin:
/**
* Configure your Gatsby site with this file.
*
* See: https://www.gatsbyjs.org/docs/gatsby-config/
*/
module.exports = {
/* Your site config here */
siteMetadata: {
title: "xxxxxxx",
author: "Subin"
},
plugins: [
"gatsby-plugin-react-helmet",
{
resolve: "gatsby-source-contentful",
options: {
spaceId: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN
}
},
"gatsby-plugin-sass",
// this plugin will pull all the files in our project system
{
resolve: "gatsby-source-filesystem",
options: {
name: "src",
path: `${__dirname}/src/`,
icon: `../src/images/favicon-32x32.png`
}
},
"gatsby-plugin-sharp",
// REMARK plugin needed to extract the markdown files and parses
{
resolve: "gatsby-transformer-remark",
options: {
plugins: [
"gatsby-remark-relative-images",
{
resolve: "gatsby-remark-images",
options: {
maxWidth: 750,
linkImagesOriginal: false
}
}
]
}
},
{
resolve: `gatsby-plugin-manifest`,
options: {
name: "xxx",
short_name: "xxxx",
start_url: "/",
background_color: "#6b37bf",
theme_color: "#6b37bf",
// Enables "Add to Homescreen" prompt and disables browser UI (including back button)
// see https://developers.google.com/web/fundamentals/web-app-manifest/#display
display: "standalone",
icon: "src/images/favicon-32x32.png" // This path is relative to the root of the site.
}
}
]
};
Remember to stop your development server and start a brand new one when modifying gatsby-config.js in order to see your changes.
Can you try this and let me know if it works as intended?

Categories

Resources