3

PropTypes is encapsulated in React object in React source code so how this statement is working-

import {PropTypes} from 'react';

Abhijeet Srivastava
  • 311
  • 1
  • 5
  • 15
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import – Felix Kling Aug 25 '16 at 06:00
  • @FelixKling, I have edited my question which is not duplicate. Please reopen it. – Abhijeet Srivastava Aug 25 '16 at 07:09
  • 1
    That's a consequence of trying to import a CommonJS module as an ES6 module. In that case Babel will treat any property of the exported object as named object. Look at the transpiled output of that code: https://babeljs.io/repl/#?evaluate=false&lineWrap=false&presets=es2015%2Creact%2Cstage-2&code=import%20abc%2C%20%7Bfoo%7D%20from%20'bar'%3B%0A%0Aconsole.log(abc%2C%20foo)%3B – Felix Kling Aug 25 '16 at 13:46

1 Answers1

4

Modules can export parts of code as default and named exports.

For example, the react library might have something like this

// named export
export function PropTypes(){/*....*/}
// defaul export
export default function(){/*....*/}

So while importing we can import default exports simply as

import React from 'module';

To import named exports we should use curly braces

import {PropTypes} from 'module';

simply we merge the above lines of code

import React, { PropTypes } from 'module'

Read more about modules here

StateLess
  • 5,344
  • 3
  • 20
  • 29
  • Thanks @ThunderBird for your input. But in React source code I see PropTypes is part of React object so wondering how can we directly import any property which is part of other object, and how importing file will know where its defined. – Abhijeet Srivastava Aug 25 '16 at 07:05
  • 1
    The link Felix King posted should provide the answers to your question, and then some. The curly brace notation is referred to as destructuring and similar notation can be used for both object and arrays. The following are definitely worth a read: [Mozilla MDN: ES6 Destructuring assignments](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), [Another useful link](http://exploringjs.com/es6/ch_destructuring.html) – Pineda Oct 28 '16 at 06:39
  • npm mandatory for import? – ManirajSS Mar 22 '21 at 09:14