Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.