簡體   English   中英

為什么 IDE 在我導入 SVG 文件以用作 React 組件時顯示錯誤?

[英]Why IDE shows me error when I import SVG file to use as React component?

我正在嘗試使用 SVG 圖標作為帶有svgr的 React 組件

一切正常。 我可以將 SVG 和 svgr 完美地轉換為 ReactComponents。

但是,當我像下面這樣導入 svg 時,我的 IDE webstorm 仍然顯示錯誤

在此處輸入圖像描述

我也在使用 typescript 和 nextjs。

什么是真正的問題? 是否僅由 IDE 引起? 或者我應該設置其他選項嗎?

這是我的配置文件

tsconfig.json

  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "baseUrl": "src/"
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "**/*.svg"
  ]
}

next.config.js

module.exports = {
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    // Note: we provide webpack above so you should not `require` it
    // Perform customizations to webpack config
    // Important: return the modified config
    config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))

    config.module.rules.push({
      test: /\.svg$/,
      use: [{
        loader: '@svgr/webpack',
        options: {
          svgoConfig: {
            plugins: {
              removeViewBox: false
            }
          }
        }
      }],
    })
    return config
  },
  webpackDevMiddleware: (config) => {
    // Perform customizations to webpack dev middleware config
    // Important: return the modified config
    return config
  },
}

並且沒有 babelrc,因為我使用的是 nextjs 給出的默認 babel 設置。

提前致謝

我自己找的。 它是由 typescript 引起的。 我必須為.svg聲明類型

我在根目錄下創建了 typing.d.ts 文件

declare module '*.svg' {
  import * as React from 'react';

  export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;

  const src: string;
  export default src;
}

IDE 不再顯示錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM