About MePublicationsContact

Autoimport React using Webpack’s ProvidePlugin

By Suresh Kumar Mukhiya
Published in Frontend Cheetseat
October 29, 2021
1 min read


It is common to import the above line if you are working with any ReactJS project. Over time, I found it repetitive and cumbersome. I started to see if the import could be done automatically, and guess what? We can by using ProvidePlugin from the webpack.

To get it working, here is what you should do. First, configure your webpack.config.js file as shown below:

webpack.config.js [Webpack]

var path = require('path')
var webpack = require('webpack')

module.exports = {
  devtool: 'eval',
  entry: [
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/'
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.ProvidePlugin({
      React: 'react'
  module: {
    loaders: [
        test: /\.js$/,
        loaders: ['react-hot', 'babel'],
        include: path.join(__dirname, 'src')

jest.setup.js [JEST]

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

// other jest setup

tsconfig.json [TypeScript]

If you have TypeScript setup, we want to make it work with the ProvidePlugin.

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

// other ts config

.eslintrc.js [ESLINT]

Once React is auto imported on all files, we often warn developers not to import React in each file. We can throw eslint warning or errors by setting up a rule as follows:

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

These configurations saved a lot of time and became handy over time. I hope someone finds this interesting and helpful. Happy Coding!


Previous Article
Fastest way to check if an object is empty
Suresh Kumar Mukhiya

Suresh Kumar Mukhiya

Software Engineer


Artificial Intelligence
Frontend Cheetseat
My Philosophy
Paper Review
Research Methods
Software Architecture

Related Posts

Insert Property and values at specific position in an Object in JavaScript
December 26, 2021
1 min
© 2022, All Rights Reserved.

Quick Links

PublicationsAbout meContact Me

Social Media