如何从外部/组件导入文件以进行反应 [英] How to import file from outside /components in react

查看:51
本文介绍了如何从外部/组件导入文件以进行反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件夹结构如下:

在我的 App.Js(在 components 文件夹下),我有:

In my App.Js (which is under the components folder), I have:

import variables from '/src/EnvVariables/variables.json';

但是,我收到一个错误:

However, I get an error:

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/.

我也试过:

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';

所有要么给出上述错误,要么说无法解析文件".

All either give the above error, or say "can't resolve file".

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

This file is in a folder that is under /src, as they said. But it still tells me it must be under the /src/ directory. How can I import my variables.json file? I don't want to just put it under "components", i prefer to better organize it.

推荐答案

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

Have you tried to import with the relative path? (with one or more ../ sections)

import variables from "../EnvVariables/variables.json"

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

Of course, if you prefer absolute paths you can setup https://webpack.js.org/configuration/resolve/, but I believe for first, you should try the first solution

这篇关于如何从外部/组件导入文件以进行反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆