Skip to content

Instantly share code, notes, and snippets.

@letelete
Last active September 1, 2024 22:08
Show Gist options
  • Save letelete/83d21eea1e5ddcbd7b8dbc3f5440c3eb to your computer and use it in GitHub Desktop.
Save letelete/83d21eea1e5ddcbd7b8dbc3f5440c3eb to your computer and use it in GitHub Desktop.
This Python script is designed to automate the process of refactoring React code in a project by replacing all occurrences of named imports from 'react' with equivalent usage of the default React import using dot notation. This is particularly useful for developers who wish to standardize their codebase to consistently use React.<name> syntax fo…

Replace react imports

This Python script is designed to automate the process of refactoring React code in a project by replacing all occurrences of named imports from 'react' with equivalent usage of the default React import using dot notation. This is particularly useful for developers who wish to standardize their codebase to consistently use React. syntax for accessing React functions and components.

Usage

  $ python replace-react-imports.py <ROOT_DIRECTORY_OF_YOUR_REACT_PROJECT>
  $ python replace-react-imports.py src

Alias in your shell config

To install the script globally, consider aliasing it in your shell config.

  replace_react_imports() {
    python ~/.zshrc.replace-react-imports.py $1
  }

Examples

Screenshot 2024-09-01 at 22 57 28

import os
import re
import sys
root_dir = sys.argv[1]
# Regular expression to match files for utility to consider
file_extension_regex = re.compile(r"^.*\.[jt]sx?$")
# Regular expression to match named imports from 'react'
named_import_regex = re.compile(
r"^import.*{([^}]*)}\s*from\s*['\"]react['\"]", re.MULTILINE
)
def replace_named_imports_with_dot_notation(content):
"""
Replace named imports from 'react' with React.<name> dot notation in the content.
"""
def replace_match(content):
match = re.match(named_import_regex, content)
if match is None:
return content
imports = [imp.strip() for imp in match.group(1).split(",")]
content = re.sub(named_import_regex, "import React from 'react'", content)
for imp in imports:
# handles named type export
imp = imp.replace("type ", "")
if imp:
content = re.sub(rf"(?<!\bReact\b\.)\b{imp}\b", f"React.{imp}", content)
return content
return replace_match(content)
def process_files_in_directory(directory):
"""
Recursively process all files in the given directory.
"""
for dirpath, _, filenames in os.walk(directory):
for filename in filenames:
if re.match(file_extension_regex, filename):
filepath = os.path.join(dirpath, filename)
with open(filepath, "r") as file:
content = file.read()
new_content = replace_named_imports_with_dot_notation(content)
if content != new_content:
with open(filepath, "w") as file:
file.write(new_content)
print(f"Updated: {filepath}")
# Start the process
process_files_in_directory(root_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment