Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing svgs with TypeScript + Webpack

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:

  • Webpack @ 2.5.0
  • TypeScript @ 2.4.0
  • svg-sprite-loader @ 3.6.2
  • awesome-typescript-loader @ 3.1.2
like image 853
amlyhamm Avatar asked Feb 20 '18 20:02

amlyhamm


People also ask

How do I use SVG in Webpack?

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/ .

Can I import SVG files as react components?

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 SVG in TypeScript?

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 !


1 Answers

Try adding

"files": [ 
  "custom.d.ts" 
]  

to your tsconfig.json

like image 88
DoctorC Avatar answered Oct 16 '22 15:10

DoctorC