英文:
why react module name doesn't have ./ or../?
问题
我是新手对react
不熟悉,想知道为什么react
的module
名称中没有./
或../
,但它们仍然正常工作,因为如果你想在自定义的module
上应用这样的命名方法,会抛出错误。
代码:
import React from 'react';
import ReactDOM from 'react-dom/client';
英文:
I'm new to react
and I'm wondering why react
module
's names don't have ./
or ../
and still they're working properly, cause if you want to apply such a naming method on a custom module
it's gonna throw an error.
code:
import React from 'react';
import ReactDOM from 'react-dom/client';
答案1
得分: 1
导入一个节点模块时,Node.js运行时知道在哪里查找它,因为它在项目的根目录中的node_modules文件夹中搜索模块。
然而,当你尝试导入一个不是节点模块且位于相对于当前文件的不同目录的文件时,你需要指定该文件的相对路径,以便运行时能找到它。这是因为这些文件的位置可能对于不同的项目和开发者是不同的,因此运行时需要具体的指示以找到该文件。
在React中,与任何其他JavaScript项目一样,你可以使用import语句导入节点模块和本地文件。当导入节点模块时,你可以简单地使用它们的名称,运行时会自动在node_modules文件夹中搜索它们。当导入本地文件时,你需要提供文件的相对路径,以便运行时能正确定位它。
英文:
When you import a node module, the Node.js runtime knows where to look for it because it searches for modules in the node_modules folder located in the root directory of your project.
However, when you try to import a file that is not a node module and is located in a different directory relative to the current file, you need to specify the relative path to that file so that the runtime can find it. This is because the location of such files can be different for different projects and different developers, and therefore the runtime needs specific instructions on how to locate the file.
In React, as with any other JavaScript project, you can import both node modules and local files using the import statement. When importing node modules, you can simply use their name, and the runtime will automatically search for them in the node_modules folder. When importing local files, you need to provide a relative path to the file so that the runtime can locate it correctly.
答案2
得分: 0
Have you used npm packages before this? The ./
denotes a relative path with respect to the current file. When you're using npm packages like react
you'll use the import like: import React from 'react'
. The same goes if it is some other npm package too. The relative path syntax is mostly used for user-created modules.
英文:
Have you used npm packages before this? The ./
denotes a relative path with respect to the current file. When you're using npm packages like react
you'll use the import like:
import React from 'react'
. The same goes if it is some other npm package too. The relative path syntax is mostly used for user-created modules.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论