如何在 NextJS 中将 svgr 与 webpack 和 TypeScript 一起使用

问题描述 投票:0回答:1

我有

svg
文件存储在单独的文件中。我想将它们加载到 React 中并用作 React 组件,如下所示:

import SampleIcon from '@/components/editor/icons/add-column-after.svg';
<SampleIcon className="my-icon" />

我安装了

svgr
并在
next.config.js
中使用,如下:

  webpack: (config) => {
    // SVG
    // Grab the existing rule that handles SVG imports
    const fileLoaderRule = config.module.rules.find((rule) =>
      rule.test?.test?.('.svg')
    );

    config.module.rules.push(
      // Reapply the existing rule, but only for svg imports ending in ?url
      {
        ...fileLoaderRule,
        test: /\.svg$/i,
        resourceQuery: /url/, // *.svg?url
      },
      // Convert all other *.svg imports to React components
      {
        test: /\.svg$/i,
        issuer: fileLoaderRule.issuer,
        resourceQuery: { not: [...fileLoaderRule.resourceQuery.not, /url/] }, // exclude if *.svg?url
        use: [
          {
            loader: '@svgr/webpack',
            options: {
              typescript: true,
              ext: 'tsx',
            },
          },
        ],
      }
    );

    // Modify the file loader rule to ignore *.svg, since we have it handled now.
    fileLoaderRule.exclude = /\.svg$/i;

    return config;
  },

它可以工作,但智能感知不起作用,即

SampleIcon
具有
any
类型。我尝试在根目录中创建
declarations.d.ts
文件并将其添加到
tsconfig.json
列表中的
include
中,但效果不佳。这是我的宣言:

declare module '*.svg' {
  import React from 'react';
  const SVG: React.VFC<React.SVGProps<SVGSVGElement>>;
  export default SVG;
}

有什么想法吗?

javascript reactjs typescript next.js
1个回答
0
投票

这很尴尬,但经过 2 小时的搜索后,我解决了这个问题:

确保

declarations.d.ts
文件位于
globals.d.ts
中的全局
tsconfig.json
文件之前:

错❌:

"include": [
    "next-env.d.ts",
    "declarations.d.ts",
    ...
]

正确✅:

"include": [
    "declarations.d.ts",
    "next-env.d.ts",
    ...
]
© www.soinside.com 2019 - 2024. All rights reserved.