简体   繁体   English

React-从外部src目录导入文件

[英]React - importing files from outside src directory

I am trying to follow along with this Medium tutorial: https://medium.com/@bryantheastronaut/react-getting-started-the-mern-stack-tutorial-feat-es6-de1a2886be50 我正在尝试遵循此中级教程: https : //medium.com/@bryantheastronaut/react-getting-started-the-mern-stack-tutorial-feat-es6-de1a2886be50

Others who have tried to follow this have commented that they have the same problem as me, although solutions to this problem are yet to be discovered in that tutorial, and similar problems on SO relate to image files, where the answer is to move the specific file to the src directory. 尝试遵循此方法的其他人则评论说,尽管我在该教程中尚未找到解决此问题的方法,但他们与我有相同的问题,SO上的类似问题也与图像文件有关,答案是将特定的文件到src目录。

The problem is referencing the data.js file, which sits at the top level (the same level as the src directory. 问题是引用了data.js文件,该文件位于最高级别(与src目录相同的级别)。

When I try to incorporate it in a file, like so: 当我尝试将其合并到文件中时,如下所示:

/CommentBox.js
import React, { Component } from 'react';
import CommentList from './CommentList';
import CommentForm from './CommentForm';
import DATA from '../data';
import style from './style';
class CommentBox extends Component {
 constructor(props) {
 super(props);
 this.state = { data: [] };
 }
 render() {
 return (
 <div style={ style.commentBox }>
 <h2>Comments:</h2>
 <CommentList data={ DATA }/>
 <CommentForm />
 </div>
 )
 }
}
export default CommentBox;

an error that says the following results: 显示以下结果的错误:

Failed to compile.
./src/CommentBox.js
Module not found: You attempted to import ../data 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/.

This SO post has a similar problem: The create-react-app imports restriction outside of src directory , however the solution is to move an image file to the src directory. 这个SO帖子有一个类似的问题: create-react-app导入限制在src目录之外 ,但是解决方案是将映像文件移动到src目录。

Has anyone figured out how to link to a file at the same level as the src directory in a react file? 有没有人想出如何链接到与React文件中src目录相同级别的文件? I don't understand what a symlink in the node_modules directory means, and I can't find a tutorial for how to make one. 我不了解node_modules目录中的符号链接的含义,也找不到如何制作符号链接的教程。

I recommend you simply put the data.js file inside your src/ directory. 我建议您仅将data.js文件放在src/目录中。 It's just mock data, right? 只是模拟数据,对不对? It should be part of src for your development. 对于您的开发,它应该是src一部分。 Just do it and get through the tutorial. 只需完成并完成本教程即可。 That's all. 就这样。 If you really were dealing with a production app, you would have ejected the app to have more flexibility over its whole configuration and thus would be able to eliminate that restriction. 如果您确实在使用生产应用程序,则可以退出该应用程序以在整个配置上具有更大的灵活性,从而可以消除该限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM