LoginSignup
2
3

More than 5 years have passed since last update.

vimでjsファイルのimport先のファイルを簡単に開く

Posted at

概要

vimにgfというカーソル配下に書かれているファイルを開くコマンドがあります。
include先を開いたりする際に便利なのですが、ES6の場合、import文で書くファイルパスは.jsが省略されているため、実際のパスと一致しないため開けません。
また、index.jsの場合はindex.js自体が省略されるため、ディレクトリが開かれてしまいます。
そこでfiletypeがjavascriptの場合は、カーソル配下にパスの記述がある場合、Ctrl+Gでimport先のファイルをsplitで開くスクリプトを書きました。下記コードを.vimrc等に貼り付けると使えるようになります。

コード

function! ReadJSFile() abort
  let s:currentPos = col('.')
  let s:colNum = s:currentPos - 1
  let s:lastPos = len(getline('.'))
  let s:fileName = ''

  while s:colNum > -1
    if getline('.')[s:colNum] =~ "\['\"\]"
      break
    end
    let s:fileName =  getline('.')[s:colNum] . s:fileName
    let s:colNum = s:colNum - 1
  endwhile
  while s:currentPos < s:lastPos
    if getline('.')[s:currentPos] =~ "\['\"\]"
      break
    end
    let s:fileName =  s:fileName . getline('.')[s:currentPos]
    let s:currentPos = s:currentPos + 1
  endwhile
  let s:fullName = simplify(expand("%:h") . '/' . s:fileName)
  if !filereadable(s:fullName)
    if isdirectory(s:fullName)
      let s:fullName = s:fullName . '/index.js'
    else
      let s:fullName = s:fullName . '.js'
    endif
  endif
  execute ':sp ' . s:fullName
endfunction
autocmd FileType javascript nmap <C-g>  :call ReadJSFile()<CR>

splitではなくてvsplitを使っている方やいま開いているファイルの代わりに開いてほしい方はexecute ':sp 'の箇所をexecute ':vs 'execute ':e 'にすることで望んでいる動作に変更できます。
Ctrl+Gが嫌な人は<C-g>の箇所を別のキーに書き換えてください。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3