【问题标题】:React how use data outside srcReact 如何使用 src 之外的数据
【发布时间】:2021-10-11 11:30:44
【问题描述】:

嘿,我如何在 App.js 中使用 data.json。我想在 App.js 中映射这些数据,但它必须位于另一个文件夹 - src 之外。

不支持 src/ 之外的相对导入。

【问题讨论】:

  • create-react-app 有一个特殊限制。它在 ModuleScopePlugin 中实现,以保证文件位于 src/ 中。这个插件确保应用程序源目录的相对导入不会到达它之外。 注意:不要从 public 文件夹导入,这将在 build 文件夹中复制,这最终会增加下载包的大小。

标签: javascript reactjs webpack import


【解决方案1】:

将json数据添加到js文件中,然后导出。然后从文件中导入并使用。

示例:

import React from 'react';

export const filterData = [
    {
        value: 'popularity.desc',
        title: 'Popularity Desc'
    },
    {
        value: 'popularity.asc',
        title: 'Popularity asc'
    },
    {
        value: 'release_date.desc',
        title: 'Release-Date Desc'
    },
    {
        value: 'release_date.asc',
        title: 'Release-Date Asc'
    },
    {
        value: 'revenue.desc',
        title: 'Revenue Desc'
    },
    {
        value: 'revenue.asc',
        title: 'Revenue Asc'
    },
    {
        value: 'original_title.desc',
        title: 'Original-Title Desc'
    },
    {
        value: 'original_title.asc',
        title: 'Original-Title Asc'
    },
    {
        value: 'vote_average.desc',
        title: 'Average-Vote Desc'
    },
    {
        value: 'vote_average.asc',
        title: 'Average-Vote Asc'
    },
    {
        value: 'vote_count.desc',
        title: 'Average-Count Desc'
    },
    {
        value: 'vote_count.asc',
        title: 'Average-Count Asc'
    }
]

【讨论】:

  • 嘿,感谢您的回答,但我无法导入它“不支持 src/ 之外的相对导入。”
  • 那就照它说的做。将 json 数据移动到 SRC 文件夹。您可以通过弹出绕过,但我不推荐它。检查这篇文章。 stackoverflow.com/questions/44114436/…
猜你喜欢
  • 2018-11-27
  • 1970-01-01
  • 2020-07-11
  • 2020-12-14
  • 1970-01-01
  • 2022-12-08
  • 2020-05-22
  • 1970-01-01
  • 2021-06-02
相关资源
最近更新 更多