简体   繁体   中英

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

Try adding

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

to your tsconfig.json

您可以在tsconfig.json中指定一个typeRoot指向 custom.d.ts 的位置。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM