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';
2
Answers
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.
Have you used npm packages before this? The
./
denotes a relative path with respect to the current file. When you’re using npm packages likereact
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.