Home > OS >  When saying import React from 'react'; where is React imported from?
When saying import React from 'react'; where is React imported from?

Time:12-17

There seems to be no corresponding folder or file named 'react'. Maybe using npm start gives the JSX file access to 'react', I don't know where 'react' is located though.

Basically, where is 'react' located?

I looked in the node_modules folder, and there is a subfolder named react. However, there is no file named React in there.

import React from 'react';

In the above line of code, I can not figure out where React is. I tried looking in the 'react' folder that is a subfolder of node_modules

CodePudding user response:

React is exported from the React package.

import React from 'react';

In the above line, you are importing a default export. You can give it any name you want instead of React.

In the React source code you can find this default export defined in package.json.

CodePudding user response:

The word React is where you assigned whatever the 'react' library exported as default.

if you open the node_modules/react/package.json file and check it you can find following line of code,

  ...
  "main": "index.js",
  "exports": {
    ".": {
      "react-server": "./react.shared-subset.js",
      "default": "./index.js" // <----------------------------- see here
    },
    "./package.json": "./package.json",
    "./jsx-runtime": "./jsx-runtime.js",
    "./jsx-dev-runtime": "./jsx-dev-runtime.js"
  },

The package.json says the entry point is index.js so if you check the content of index.js, (exports["."]["default"] says use index.js for default import ( ie import DefaultReact from 'react' ))

'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/react.production.min.js');
} else {
  module.exports = require('./cjs/react.development.js');
}

This is not just a react specific thing, you can learn how to create custom packages from here.

  • Related