Skip to content

Instantly share code, notes, and snippets.

@ryanwilsonperkin
Created April 6, 2018 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanwilsonperkin/3501bf0e1fdf24d477402b522feda423 to your computer and use it in GitHub Desktop.
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
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