简体   繁体   English

导入节点模块与自定义组件 ES6、React

[英]Importing node module vs custom component ES6, React

Can someone help me to understand how es6 import works?有人可以帮助我了解 es6 import 的工作原理吗?

As I know to import node modules I can write name of module without mentioning path ex:据我所知,要导入节点模块,我可以在不提及路径 ex 的情况下编写模块名称:

import React from 'react';

However to import any custom component, I have to give path like:但是要导入任何自定义组件,我必须提供如下路径:

import Header from "./components/Header";

Or to import scss或者导入scss

import "../../scss/components/Header.scss";

Can someone tell me how it works, why in case of nodule module I do not need to give path?有人可以告诉我它是如何工作的,为什么在结节模块的情况下我不需要给出路径?

When you do not give path it will directly look into node_modules directory and find the provided module.当您不提供路径时,它将直接查看node_modules目录并找到提供的模块。

So,所以,

import React from 'react';

It will look into node_modules/react and import React from index.js since we have not explicitly defined any path after react directory.它将查看node_modules/react并从index.js导入React ,因为我们没有在react目录之后明确定义任何路径。 So, it is similar to react/index.js .所以,它类似于react/index.js If you have to import something else rather than index.js then we'll need to specify the file path as well.如果您必须导入其他内容而不是index.js ,那么我们还需要指定文件路径。 For eg.例如。 module/somefile.js . module/somefile.js

Now, when you specify path that is starting with / or ./ or ../ it will not look into node_modules but it will look in to the directory.现在,当您指定以/./../开头的路径时,它不会查看node_modules但它会查看目录。 You may look into my another post for more detail how linking path works.您可以查看我的另一篇文章以了解链接路径如何工作的更多详细信息。

In the linked post, it has no ./ path described.在链接的帖子中,它没有描述./路径。 So let me tell you that it will find the current project directory.所以让我告诉你它会找到当前的项目目录。 For eg.例如。 your project folder is app and you specify ./mydir/myfile then it will look into app/mydir/myfile.js .您的项目文件夹是app并且您指定./mydir/myfile然后它将查看app/mydir/myfile.js There's no need to specify .js extension necessarily if you have to import javascript file.如果必须导入 javascript 文件,则无需指定.js扩展名。 It will automatically match the .js extension.它将自动匹配.js扩展名。 But if you have to import other files for eg.但是,如果您必须导入其他文件,例如。 .css then you must specify the extension as well. .css那么您还必须指定扩展名。

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

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