amlyhamm
amlyhamm

Reputation: 1150

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:

Upvotes: 10

Views: 9943

Answers (2)

DoctorC
DoctorC

Reputation: 115

Try adding

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

to your tsconfig.json

Upvotes: 3

lorefnon
lorefnon

Reputation: 13115

You can specify a typeRoot in your tsconfig.json pointing to the location of custom.d.ts.

Upvotes: 0

Related Questions