2017-05-15 28 views
0

我正在尝试编写一个Vim命令来跟踪js/ES6文件中的require/import引用(尊重模块解析器别名)。“require.resolve不是一个函数”在babel-node eval模式下

如果键入babel-node拖放到REPL模式,我可以这样做:

> require.resolve('~'); 
/properly/resolved/path 

但是,如果我尝试EVAL同样表达(我需要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),但随后被插入的命令,巴贝尔尝试后执行功能(没有找到它的一些重一个儿子)。

我在这里做错了什么?这是一个错误?

+0

我不知道Vim和参与这一问题。 – romainl

+0

删除标签。 – sdeleon28

+0

由于解决方法是纯Vim,因此添加了Vim标记 – sdeleon28

回答

0

我工作围绕这一问题的临时文件和一些相当恶劣的vim脚本:

" 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>