Created
September 23, 2021 23:36
-
-
Save itsjohncs/76456b91e8aca65daa01d11ff1db9836 to your computer and use it in GitHub Desktop.
Adds a .js extension to all your imports!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import re | |
import sys | |
import os | |
import_re = re.compile(r'^(import .*|}) from "(\.\.?/[^"]+)";?$', re.MULTILINE) | |
target_file = sys.argv[1] | |
def replace_import(match): | |
with_file = lambda path: f'{match.group(1)} from "{path}";' | |
to_import = match.group(2) | |
if os.path.isfile(to_import): | |
return match.group(0) | |
elif os.path.isdir(to_import): | |
return with_file(os.path.join(to_import, "index.js")) | |
elif os.path.isfile(to_import + ".js"): | |
return with_file(to_import + ".js") | |
raise RuntimeError(f"Can't deal with import path {to_import}") | |
with open(target_file) as f: | |
os.chdir(os.path.dirname(target_file)) | |
sys.stdout.write(import_re.sub(replace_import, f.read())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment