如何在反应中从外部/组件导入文件

joe*_*oey 2 reactjs

我的文件夹结构如下:

在此输入图像描述

在我的 App.Js(位于组件文件夹下)中,我有:

import variables from '/src/EnvVariables/variables.json';
Run Code Online (Sandbox Code Playgroud)

但是,我收到错误:

You attempted to import /src/EnvVariables/variables.json which falls
outside of the project src/ directory. Relative imports outside of
src/ are not supported. You can either move it inside src/, or
add a symlink to it from project's node_modules/.
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

import variables from './src/EnvVariables/variables.json';
import variables from '/src/EnvVariables/variables.json';
import variables from '/src/EnvVariables/variables.json';
import variables from '/EnvVariables/variables.json';
import variables from './EnvVariables/variables.json';
Run Code Online (Sandbox Code Playgroud)

所有这些要么给出上述错误,要么说“无法解析文件”。

正如他们所说,该文件位于 /src 下的文件夹中。但它仍然告诉我它必须在 /src/ 目录下。如何导入我的variables.json 文件?我不想只是将它放在“组件”下,我更喜欢更好地组织它。

Yoz*_*ozi 5

您是否尝试过使用相对路径导入?(包含一个或多个../部分)

import variables from "../EnvVariables/variables.json"
Run Code Online (Sandbox Code Playgroud)

当然,如果您更喜欢绝对路径,您可以设置https://webpack.js.org/configuration/resolve/,但我相信首先,您应该尝试第一个解决方案