Yusinto Ngadiman
August 20, 2020·1 min read

Automatically import react


import React from 'react';

It's the most common import you type in your project. Won't it be cool if somehow we don't have to do this all the time? Enter webpack ProvidePlugin. This plugin allows us to import react automatically where it's required, thus saving our lives so we can do other things.

If you are using react with typescript, jest and eslint, here's what you need to do to get it all working:


const { ProvidePlugin } = require("webpack");

module.exports = {
  plugins: [
    new ProvidePlugin({
      React: "react" // automatically import react where needed
  ], // other webpack config


  "compilerOptions": {
    "allowUmdGlobalAccess": true, // make typescript work with ProvidePlugin
    // other compiler options

  // other ts config


// simulate ProvidePlugin for our tests using a global variable
window.React = require('react');

// other jest setup


module.exports = {
  rules: {
    // Prevent default react imports like import React from 'react' 
    // but still allows other named react imports.
    'no-restricted-imports': [
        paths: [
            name: 'react',
            importNames: ['default'],
            message: 'React default is automatically imported by webpack.',

    // other eslint rules

The result is you no longer need to import the default react export, but you will still need to manually import other named exports. You can easily extend the webpack config to include react's named exports and other imports as well like react-dom and react-router. However I would recommend using this technique sparingly to avoid having too much config magic in your project.

Have fun coding!