【问题标题】:Why IDE shows me error when I import SVG file to use as React component?为什么在我导入 SVG 文件以用作 React 组件时 IDE 显示错误?
【发布时间】:2020-10-02 01:10:55
【问题描述】:

我正在尝试使用 SVG 图标作为带有 svgr 的 React 组件

一切正常。我可以将 imoport 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 设置。

提前致谢

【问题讨论】:

    标签: reactjs typescript svg next.js


    【解决方案1】:

    我自己找到的。它是由打字稿引起的。我必须为.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 不再显示错误

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      相关资源
      最近更新 更多