Skip to content

Instantly share code, notes, and snippets.

@Genzer
Last active August 29, 2019 07:57
Show Gist options
  • Save Genzer/73cac3c12f92a7817b69e371fc9832dc to your computer and use it in GitHub Desktop.
Save Genzer/73cac3c12f92a7817b69e371fc9832dc to your computer and use it in GitHub Desktop.
Find and replace Javascript relative imports.
This file is solely for being Gist's name.

Replace Javascript Relative-Path Import Statements

This simple Python module will try to resolve your Javascript relative import statements with an package-ish one.

For examples:

If your project's structure is like this:

app/
  logging/
    logger.js
    index.js
  customers/
    processes/
      onboarding/
        registration.js

and in registration.js you want to use the logger module.

import { Logger } from '../../../logging';

This looks ugly. So this script will try to replace it with

import { Logger } from 'app/logging';

Of course, after this replacement, you have to configure you transpiler (i.e: Babel) to resolve the path.

For example, in your package.json:

// package.json
{
  "babel": {
		"plugins": [
			["module-resolver", {
				"root": ["./app"],
				"alias": {
					"app": "./app"
				}
			}]
		]
	}
}

Usage:

./replace_relative_import.py your/app/then/some/javascript/module.js

Bulk Replacement

This gist is shipped with a Shell script to find and replace all *.js files.

# Default mode
# ./bulk_change.sh . *.js
./bulk_change.sh

# or
./bulk_change.sh app '*customer*.js'
#!/usr/bin/env bash
set -e
cwd=${1:-"$(pwd)"}
filter=${2:-'*.js'}
target_src=$(dirname $cwd)
root_src=$(basename $cwd)
# Resolve the directory containing the scripts
script_src=$(realpath $(dirname ${BASH_SOURCE}))
echo "[info] - JS files in directory ${root_src} in ${target_src}"
cd $target_src
find ${root_src} -path ${filter} -type f | xargs -I {} sh -c "echo {} && ${script_src}/replace_relative_import.py {}"
#!/usr/bin/env python3
import os
import sys
import fileinput
import re
from pathlib import Path
"""
This simple Python module will try to resolve your Javascript **relative** `import`
statements with an package-ish one.
For examples:
If your project's structure is like this:
```
app/
logging/
logger.js
index.js
customers/
processes/
onboarding/
registration.js
```
and in `registration.js` you want to use the `logger` module.
```javascript
import { Logger } from '../../../logging';
```
This looks ugly. So this script will try to replace it with
```javascript
import { Logger } from 'app/logging';
```
Of course, after this replacement, you have to configure you transpiler (i.e: Babel)
to resolve the path.
For example, in your `package.json`:
```json
// package.json
{
"babel": {
"plugins": [
["module-resolver", {
"root": ["./app"],
"alias": {
"app": "./app"
}
}]
]
}
}
```
Usage:
```shell
./replace_relative_import.py your/app/then/some/javascript/module.js
```
"""
# Usage:
# ./replace_relative_import.py your/app/then/some/javascript/module.js
file = sys.argv[1]
cwd = Path(file).parent
import_with_relative_path = re.compile('^import.*from \'((?:\.\.\/)+.*)\';?$')
for line in fileinput.input(file, inplace=True):
match = import_with_relative_path.match(line)
if match:
import_relative_path = match.groups()[0]
relative_path = Path(import_relative_path)
resolved_absolute_path = os.path.normpath(os.path.join(cwd, relative_path))
print(line.replace(import_relative_path, resolved_absolute_path), end='')
else:
print(line, end=''),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment