I have a pretty simple Webpack + TypeScript setup and am trying to import svgs. I'm using svg-sprite-loader
and it works well if I require()
my svgs like the following:
require('./assets/alert.svg')
--
However, I'd prefer to use the following:
import alert from './assets/alert.svg'
With that, I get the following error:
TS2307: Cannot find module './assets/alert.svg'.
I have a custom.d.ts
file in my project root (after reading this: https://webpack.js.org/guides/typescript/#importing-other-assets). It looks like this:
declare module '*.svg' {
const content: any;
export default content;
}
My tsconfig
looks like:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"lib": ["es6", "dom"]
},
"exclude": [
"**/*.spec.ts"
]
}
And finally, my webpack set up includes:
module: {
rules: [
{
test: /\.ts$/,
use: `awesome-typescript-loader`
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.svg$/,
loader: 'svg-sprite-loader'
}
]
}
I'm trying to understand how that custom.d.ts
file comes into play. Is there something I need to add in my tsconfig
?
Also, for versions, I'm using:
To inline an SVG, you have to use the IMG HTML tag and add an inline attribute. Webpack will replace the tag and inline the XML from the file. Note: the image path is a relative path from the project root. It's because I add src/img/ and not img/ .
JSX supports the svg tag, so we can copy-paste the SVG directly into our React components. This method is straightforward as it helps you take full advantage of SVGs without using a bundler. The approach is possible because SVGs are in XML format, just like HTML.
What is the type of the <svg> element in TypeScript? The interface type of <svg> elements in an *. svg document (i.e. the SVG DOM) is SVGElement . The type of an <svg> element within a HTML document (i.e. the HTML DOM) is actually a prototype-less object that implements both HTMLElement and SVGElement !
Try adding
"files": [
"custom.d.ts"
]
to your tsconfig.json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With