Skip to content

Instantly share code, notes, and snippets.

@johnnymo87
Created April 21, 2023 15:50
Show Gist options
  • Save johnnymo87/5dcdf8739af4ea5d071fd5380ec5cec9 to your computer and use it in GitHub Desktop.
Save johnnymo87/5dcdf8739af4ea5d071fd5380ec5cec9 to your computer and use it in GitHub Desktop.
How I converted all javascript files in a codebase from amd imports to commonjs
function! ReplaceRequireJS()
StripTrailingWhitespaces
normal gg
call search(')')
let @e= line('.')
call MaybeAddNewLineBelow()
call PrependModuleExports()
normal gg
normal @eJ
normal ^"aD
exe 'read !ruby replace_requirejs.rb "' . @a . '"'
normal j<G
normal ggdd
endfunction
function! MaybeAddNewLineBelow()
normal j
if len(getline(line('.'))) != 0
normal O
endif
endfunction
function! PrependModuleExports()
normal G
call search('\v^\s{2}\w+', 'b')
if getline('.')[col('.')-1] == '}'
" note that ^ and 0 are switched in my dotfiles!
normal %^
endif
normal xi module.exports =
endfunction
nnoremap ,jj :call ReplaceRequireJS()<CR>
REGEX = /\[(.*?)\].*?\((.*?)\)/
def match_path_string_and_name_string(string)
_, path_string, name_string = REGEX.match(string).to_a
raise(
"matched '#{path_string}' and '#{name_string}' from '#{string}'"
) unless path_string && name_string
[path_string, name_string]
end
def strip(string)
string.gsub(',', '').gsub('"', '').gsub("'", '')
end
def paths_zipped_with_names(path_string, name_string)
strip(path_string).split.zip(
strip(name_string).split
)
end
def import_lines_from(path_name_pairs)
counter = 0
path_name_pairs.map do |path, name|
name ||= "UnusedModule#{counter += 1}"
"#{name} = require('#{path}')"
end
end
if __FILE__ == $0
path_string, name_string = match_path_string_and_name_string(ARGV[0])
paths_zipped_with_names = paths_zipped_with_names(path_string, name_string)
import_lines_from(paths_zipped_with_names).each do |import_line|
puts import_line
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment