Created
April 6, 2018 03:24
-
-
Save ryanwilsonperkin/3501bf0e1fdf24d477402b522feda423 to your computer and use it in GitHub Desktop.
Update relative imports in JS files to be absolute based on current path
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
import os | |
import re | |
import sys | |
ROOT_DIR = 'project-name' | |
PATTERN = re.compile( | |
"""(?P<prefix>.*from *['"])""" | |
"""(?P<path>\..*)""" | |
"""(?P<suffix>['"].*)""" | |
) | |
def replace_line(file_path, line): | |
if not PATTERN.match(line): | |
return line | |
old_import_path = PATTERN.match(line).group('path') | |
new_import_path = os.path.relpath( | |
os.path.join( | |
ROOT_DIR, | |
os.path.dirname(file_path), | |
old_import_path, | |
) | |
) | |
return re.sub( | |
PATTERN, | |
r'\g<prefix>{}\g<suffix>'.format(new_import_path), | |
line | |
) | |
# usage: python update.py path/to/file.js | |
# Updates all relative imports in file.js to be absolute from current path | |
if __name__ == '__main__': | |
file_path = sys.argv[1] | |
with open(file_path) as in_file: | |
old_lines = in_file.readlines() | |
with open(file_path, 'w') as out_file: | |
for line in old_lines: | |
out_file.write(replace_line(file_path, line)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment