简体   繁体   English

Javascript ES6模块名称解析

[英]Javascript ES6 modules name resolution

I'm absolutely sure, that I'm asking a silly question, but I really do not understand how this line of code works我绝对确定,我在问一个愚蠢的问题,但我真的不明白这行代码是如何工作的

import React from 'react';

My question: who and where searches for 'react' name?我的问题:谁和在哪里搜索'react'名称?

For example, this site tells me, that for module-name I should use relative of absolute path, eg例如,这个站点告诉我,对于module-name ,我应该使用绝对路径的相对路径,例如

import React from './react';

or或者

import React from '/home/user/react';

I thought that 'react' is same as './react' but I've created ReactJS applcation via create-react-app command and didn't find any file named react.js in application folder.我认为'react''./react'相同,但我通过create-react-app命令创建了 ReactJS 应用程序,但在应用程序文件夹中没有找到任何名为react.js的文件。

So, obviously there is some tool or rule by which module name has been resolved to a proper file, but I cannot find proper documentation about this.因此,显然有一些工具或规则已将模块名称解析为正确的文件,但我找不到关于此的正确文档。

Import statements are importing packages by name from the node_modules directory in your app , which is where they're saved when you run an installation command such as npm install or yarn inside your app.导入语句是从应用程序的node_modules目录中按名称导入包,当您在应用程序中运行npm installyarn等安装命令时,它们会保存在该目录中。

When you write:当你写:

import React from 'react';

As far as you're concerned, it's as if you'd written:就您而言,就好像您写过:

import React from './node_modules/react/index.js';

Importing by package name means you don't have to be aware of how a given package is structured or where your node_modules directory is relative to your javascript file.通过 package 名称导入意味着您不必知道给定 package 的结构或node_modules目录相对于 javascript 文件的位置。

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

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