我试图编写一个Vim命令来遵循js / ES6文件中的require / import引用(尊重模块解析器别名)。
如果我输入babel-node
并进入REPL模式,我可以执行以下操作:
> require.resolve('~');
/properly/resolved/path
但是,如果我尝试评估相同的表达式(我需要eval来指定运行时Vim的路径),我得到:
$ babel-node -e 'console.log(require.resolve("~"))'
[eval]:1
console.log(require.resolve("./lib/webapp/lib"));
^
TypeError: require.resolve is not a function
at [eval]:1:-41
at ContextifyScript.Script.runInThisContext (vm.js:23:33)
at Object.runInThisContext (vm.js:95:38)
at _eval (/usr/local/lib/node_modules/babel-cli/lib/_babel-node.js:99:23)
at Object.<anonymous> (/usr/local/lib/node_modules/babel-cli/lib/_babel-node.js:119:16)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
看起来波浪线已正确解析(~
指向./lib/webapp/lib
)但随后插入到命令中,并且babel尝试执行该功能(由于某种原因未找到它)
我在这里做错了吗?这是一个错误吗?
答案 0 :(得分:0)
我用一个临时文件和一些相当讨厌的vimscript解决了这个问题:
" Follow JavaScript references with proper babel (and module-resolver)
" resolution (required a git repo in the project's root)
function FollowJsReference()
" Find the reference and yank it into the r register
exec "normal ^f'\"ryi'"
" Create a file at the root with the code for babel-node to resolve the
" reference. Ideally, I'd do this with babel-node's eval, but it errors out.
" Instead, I create a script, evaluate it then delete it.
let s:script_content = 'console.log(require.resolve("' . @r . '"));'
let s:create_command = 'tee `git rev-parse --show-toplevel`/___resolve.js'
call system(s:create_command, s:script_content)
" Run babel-node from the root dir
let s:babel_command = 'cd `git rev-parse --show-toplevel` && babel-node ./___resolve.js'
let s:out = system(s:babel_command)
exec ":edit " . s:out
" Clean up
let s:delete_command = 'rm `git rev-parse --show-toplevel`/___resolve.js'
call system(s:delete_command)
endfunction
nnoremap <Leader>gj :call FollowJsReference()<CR>