Never `import React from ‘react’` again, thanks to Webpack’s ProvidePlugin

How many times a day do you write this import statement?

import React from ‘react’

Or this guy?

import ReactDOM from ‘react-dom’

A few weeks ago, a colleague at Udacity showed me a trick that eliminates the need for repetitive import statements in your code. The magic starts on line 18, with Webpack’s ProvidePlugin:

When Webpack builds your JavaScript, it will load the ‘react’ module whenever the identifier ‘React’ is declared in your code. So now you can use:

React.createClass(…)

…without having to import ‘react’ explicitly at the top of your component file.

Webpack’s ProvidePlugin isn’t limited to React dependencies, of course. You can use it to load all your frequently used modules.

This not only leads to fewer build errors, it also gets rid of big import blocks like this at the top of your code:

import ReactDOM from ‘react-dom’
import _ from 'lodash'
import $ from 'jquery'
import cssModule from 'react-css-modules'

I feel an irrational amount of happiness about such things, don’t you?