【问题标题】:How to import a folder of svg files into react as ReactComponents如何将 svg 文件的文件夹导入到 ReactComponents 中
【发布时间】:2022-01-20 02:10:36
【问题描述】:

我正在为我的前端(使用 CRA 制作)使用 react 制作一个实时纸牌游戏,并且我将我所有的卡片作为 .svg 文件存储在 src 文件夹的子文件夹中。我在其他问题中看到,对于单个文件,您可以使用 import {ReactComponent as Image} from 'whatever.svg',而对于整个文件夹,您可以使用 require.context()。虽然 import 语句有效,但 require.context 方法只是为我提供了 /static/media/whatever.randomStuff.svg 文件,我只能通过向站点上的该位置发出 http(s) 请求来导入这些文件。我曾尝试在 require.context 函数中使用@svgr/webpack,但即使手动安装,它也会给我相同的输出。有没有办法让我使用 import 语句或其他方法将该文件夹中的所有 .svg 文件作为文件中的 ReactComponents 导入,而不必发出 http(s) 请求?

【问题讨论】:

标签: reactjs svg


【解决方案1】:

我正在寻找的答案来自另一个问题的this answer。发帖时我不知道的一件事是 react-scripts 使用的 webpack 版本(v4.44.2)已经有@svgr/webpack,所以用 npm 手动安装它基本上没用,因为它可能已经在使用它首先生成/static/media/fileName.randomStuff.svg 文件。最后我在 svg 文件夹中使用了一个中间文件并这样做了:

interface CardCache {
    [key: string]: React.FunctionComponent<React.SVGAttributes<SVGElement>>;
}
const cache: CardCache = {};

/* eslint import/no-webpack-loader-syntax: off */
const files = require.context("!svg-react-loader?name=card!./", true, /\.svg$/);

files.keys().forEach(path => {cache[path] = files(path)});

export {cache};

我使用 eslint 注释是因为我不想将 react-scripts 替换为 react-app-rewired 之类的东西,这样我就可以访问 webpack.config.json 文件。

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 2021-05-26
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多