简体   繁体   中英

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

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.

The problem is referencing the data.js file, which sits at the top level (the same level as the src directory.

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.

Has anyone figured out how to link to a file at the same level as the src directory in a react file? 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.

I recommend you simply put the data.js file inside your src/ directory. It's just mock data, right? It should be part of src for your development. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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