Yusinto Ngadiman
August 20, 2020·1 min read

Automatically import react

hero

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:

webpack.config.js

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

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

tsconfig.json

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

  // other ts config
}

jest.setup.js

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

// other jest setup

.eslintrc.js

module.exports = {
  rules: {
    // Prevent default react imports like import React from 'react' 
    // but still allows other named react imports.
    'no-restricted-imports': [
      'error',
      {
        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!