Last active
April 14, 2019 16:12
-
-
Save dioptx/0ac732578d9d91a6e1ef7e20282b3ec1 to your computer and use it in GitHub Desktop.
index.js creation with Python from a dynamic asset structure
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
from pathlib import Path | |
from pprint import pprint | |
import os, json | |
root_path = Path('YOUR_ROOT_PATH') | |
assets = {} | |
def add_to_dict(root_dict, components, path_to_root): | |
component = components.pop(0) | |
if component not in root_dict.keys(): | |
if len(components) !=0: | |
root_dict[component] = {} | |
else: | |
component = component.split('.')[0] | |
root_dict[component] = "require('./{0}')".format(path_to_root) | |
new_root = root_dict[component] | |
if len(components) == 0: | |
# Exit | |
return | |
else: | |
# Recursion | |
add_to_dict(new_root, components, path_to_root) | |
pathlist = sorted(root_path.glob('**/*.jpg')) | |
for path in pathlist: | |
path_in_str = str(path) | |
print(path_in_str) | |
components = list(path.parts[len(root_path.parts):]) | |
add_to_dict(assets,components, os.path.join(*[path for path in components])) | |
str_assets = json.dumps(assets, indent=4, sort_keys=True).replace('"','') | |
js_string = 'const assets = ' + str_assets + '; \n\nexport default assets;' | |
with open('./index.js', 'w') as file: | |
file.write(js_string) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment