How to import SVG in ReactJS with craco? - reactjs

I'm struggling to import SVG's when I'm using craco in my react app.
It's suggested to use #svgr/webpack but I'm not sure how to put it into my craco.config.js
My current setup as per this (I prob shouldn't follow someone's config that doesn't work and expect it to work tho) that does not work:
// craco.config.js
const CracoAlias = require("craco-alias");
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
baseUrl: "./src",
tsConfigPath: "./tsconfig.paths.json"
}
},
],
webpack: {
configure: (config, { env, paths }) => {
config.module.rules.push({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
return config;
}
}
};
The craco.config.js webpack documentation is here but it's so confusing to me without concrete examples.
Also to note:
Writing import {ReactComponent as mySvg} from "./mySvg.svg" doesn't work because it doesn't recognize it as a ReactComponent.
If I try importing directly via import mySvg from "./mySvg.svg" Typescript doesn't recognize the file.
What I'm currently doing is putting the svg into a React component and using that but it's a nightmare doing that every time. I also put this in #types/custom.d.ts, but it still doesn't work when put into <img src={mySvg} />
// #types/custom.d.ts
declare module "*.svg" {
const content: any;
export default content;
}

import {reactComponent as GoogleLogo} from "../assets/image/googlelogo.svg;
GoogleLogo is component and reactComponent is a required magic string
i find the fix your problem in Adding svgr to create-react-app via craco

Related

Using the MUI's SvgIcon with the "component" prop results in a blank page

My code looks like this:
import DrawIcon from "frontend/public/svgs/draw.svg";
export default function SomeIcon(): JSX.Element {
return <SvgIcon component={DrawIcon}/>
}
For some reason, whenever I use the component prop, the app renders a blank page and I get no errors.
I'm trying to use SVGR as shown in the MUI documentation.
I'm making a Next.js app so I added this to my next.config.js file:
webpack: (config) => {
config.module.rules.push({
test: /\.svg$/,
issuer: /\.[jt]sx?$/,
use: ['#svgr/webpack'],
});
return config;
},
And installed SVGR using npm install #svgr/webpack --save-dev.
I can't figure out why this happens or how to fix it.

How to add #svgr/webpack to craco.config?

Similar to this question - I want to be able to load svgs in my reactjs app using the following syntax below. I'm using craco so it doesn't work by default.
import {ReactComponent as MyLogo} from "./svg/MyLogo.svg";
// ...
return (
<MyLogo />
);
My craco.config.js is...
const CracoAlias = require("craco-alias");
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
// baseUrl SHOULD be specified
// plugin does not take it from tsconfig
baseUrl: "./src",
/* tsConfigPath should point to the file where "baseUrl" and "paths"
are specified*/
tsConfigPath: "./tsconfig.paths.json"
}
},
],
webpack: {
configure: (config, { env, paths }) => {
config.module.rules.push({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
return config;
}
}
};
Not sure if this is the right way to hook up #svgr/webpack to my craco config.
Currently, it doesn't work and errors with this...
import {ReactComponent as MyLogo} from "./MyLogo.svg";
// Error Module '"*.svg"' has no exported member 'ReactComponent'.
// Did you mean to use 'import ReactComponent from "*.svg"' instead?
How can I make this work properly using craco?

Rollup plugin postcss does not inject css imported from node_modules

Here is my rollup config
// rollup.config.js
const postcss = require('rollup-plugin-postcss');
const autoprefixer = require('autoprefixer');
module.exports = {
rollup(config, _options) {
config.plugins.push(
postcss({
plugins: [
autoprefixer(),
],
extensions: ['.css'],
modules: false,
extract: false,
}),
);
return config;
},
};
So if I import css file local from a relative path, it gets injected but I import from node_modules it doesn't
import React from 'react';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
// The following works if I copy the file locally
// import './ReactToastify.css';
What am I doing wrong here?
I came across exactly the same problem and I think I found the solution. The trick here is to use rollup-plugin-postcss (or also rollup-plugin-styles) in combination with #rollup/plugin-node-resolve.
My rollup.config.js looks something like this:
import { nodeResolve } from '#rollup/plugin-node-resolve'
import postcss from 'rollup-plugin-postcss'
// import styles from 'rollup-plugin-styles'
export default {
...
plugins: [
postcss(),
// styles(),
nodeResolve({
extensions: ['.css']
})
]
};
As far as I can tell, for my simple case, it doesn't matter if you use postcss or styles plugins. Both work the same.

I need help nextjs styling

I import component level module scss as
import styles from './SideDrawer.module.scss';
then apply the scss below
<div className={styles.container}></div>
However, the scss is not taking effect.
Note: If I use
import './SideDrawer.module.scss';
then apply the scss below and it works
<div className="container"></div>
next.config.js - shows built-in css is disabled
const withSass = require("#zeit/next-sass");
module.exports = withSass({
webpack(config) {
config.module.rules.push({
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
issuer: {
test: /\.(js|ts)x?$/,
},
use: ['#svgr/webpack'],
});
return config;
},
});
How can I make the first import style to work?
This seems to be a limitation on the part of Next.js. Revert back to built-in Sass. Thank you all

React Storybook SVG Failed to execute 'createElement' on 'Document'

I'm trying to add Storybook to an existing React app but getting errors with imported svg files. The svg is imported and used like:
import Border from './images/border.inline.svg'
...
<Border className="card__border" />
This works when the app is run and built, but I get an error in Storybook. How come?
Failed to execute 'createElement' on 'Document': The tag name provided ('static/media/border.inline.258eb86a.svg') is not a valid name.
Error: Failed to execute 'createElement' on 'Document': The tag name provided ('static/media/border.inline.258eb86a.svg') is not a valid name.
The default webpack.config.js has:
...
{
test: /\.inline.svg$/,
loader: 'svg-react-loader'
},
...
Also, the existing code uses webpack 3, and I'm using Storybook V4.
This is happening because Storybook's default webpack config has its own svg config:
{
test: /\.(svg|ico|jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|cur|ani)(\?.*)?$/,
loader: 'file-loader',
query: { name: 'static/media/[name].[hash:8].[ext]' }
},
I'm pretty sure this is the cause, because you can see the path outlined in error message: query: { name: 'static/media/[name].[hash:8].[ext]' } -> static/media/border.inline.258eb86a.svg
The solution can be to find the existing loader & change / or add an exclude rule to it. Here's an example of a custom .storybook/webpack.config.js:
// storybook 4
module.exports = (_, _, config) => {
// storybook 5
module.exports = ({ config }) => {
const rules = config.module.rules;
// modify storybook's file-loader rule to avoid conflicts with your inline svg
const fileLoaderRule = rules.find(rule => rule.test.test('.svg'));
fileLoaderRule.exclude = /\.inline.svg$/;
rules.push({
test: /\.inline.svg$/,
...
}],
});
return config;
};
It appears that Storybook V6 they have changed the default Webpack config. I found that the above answers didn't work for me.
They no longer have an SVG rule, therefore testing for SVG will either error or return back undefined.
There is a oneOf rule on the module.rules which contains a loader without a test as the last rule:
{
loader: '/Users/alexwiley/Work/OneUp/resources/client/node_modules/react-scripts/node_modules/file-loader/dist/cjs.js',
exclude: [Array],
options: [Object]
}
This is the culprit, you need to make sure that the file load is excluding all inline SVG file otherwise it will error.
Add the following to your .storybook/main.js file:
webpackFinal: async(config, { configType }) => {
config.module.rules.forEach((rule) => {
if (rule.oneOf) {
// Iterate over the oneOf array and look for the file loader
rule.oneOf.forEach((oneOfRule) => {
if (oneOfRule.loader && oneOfRule.loader.test('file-loader')) {
// Exclude the inline SVGs from the file loader
oneOfRule.exclude.push(/\.inline\.svg$/);
}
});
// Push your SVG loader onto the end of the oneOf array
rule.oneOf.push({
test: /\.inline\.svg$/,
exclude: /node_modules/,
loader: 'svg-react-loader', // use whatever SVG loader you need
});
}
});
return config;
}
In Storybook 6, You have to import it like this:
import { ReactComponent as Border } from './images/border.inline.svg'
Try that if it also works for your version since this question is from a year ago.
This is another way that fixed the issue for me
import Border from './images/border.inline.svg'
And then in your code
<img src={Border} alt="Border" className="w-25"/>
I got it working with
...
module.exports = {
module: {
rules: [
{
test: /\.inline.svg$/,
loader: 'svg-react-loader'
}
]
}
}
For me it was happening as I was using wrong tag name:
import React from 'react';
import RMDBLogo from '../../images/react-movie-logo.svg';
import TMDBLogo from '../../images/tmdb_logo.svg';
import { Wrapper, Content,LogoImg,TMDBLogoImg } from './Header.styles';
const Header = () => (
<Wrapper>
<Content>
<LogoImg src={RMDBLogo} alt='RMDBLogo' />
<TMDBLogo src={TMDBLogo} alt='TMDBLogo'/>
</Content>
</Wrapper>
);
export default Header;
I had imported TMDBLogoImg component while I'm using TMDBLogo tag inside Content tag.

Resources