如何在 Vim 中格式化 JS 代码? [英] How can I format JS code in Vim?

查看:38
本文介绍了如何在 Vim 中格式化 JS 代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一点 JavaScript...

I have this bit of JavaScript...

 15   $('.ajax_edit_address').each(function() {
 16     $(this).ajaxForm({
 17       target: $(this).parents('table.address').find('tr.address_header').children(':first'),
 18       success: function(response) {
 19         $('input, select, textarea', '.ajax_edit_address').removeClass('updating');
 20       }
 21     });
 22   });

这是我喜欢的格式.但是假设我刚刚打完一些东西,我想把它整理一下.所以我在上面运行 Vim 代码格式化程序...

That's formatted the way I like it. But let's say I had just finished typing something and I wanted to tidy it up. So I run the Vim code formatter on it...

=7j

结果是...

 15   $('.ajax_edit_address').each(function() {
 16       $(this).ajaxForm({
 17 target: $(this).parents('table.address').find('tr.address_header').children(':first'),
 18 success: function(response) {
 19 $('input, select, textarea', '.ajax_edit_address').removeClass('updating');
 20 }     
 21 }); 
 22       });

Vim 似乎在将函数作为方法参数时遇到问题.

Vim seems to have trouble with functions as method arguments.

这是我认为是我的 .vimrc 的相关部分...

Here is what I think is the relevant part of my .vimrc...

:set cindent shiftwidth=2

" indent depends on filetype
:filetype indent on

:filetype plugin on

是否需要安装或配置其他东西来格式化 JS 代码?

Is there something else that needs to be installed or configured to format JS code?

推荐答案

最大的问题似乎是 cindent 不识别这种类型的语法:

The biggest issue seems to be the cindent doesn't recognize this type of syntax:

test({
  var b = 2;
});

它会变成这样:

test({
    var b = 2;
    });

如果您处理这种情况,我想对于 jQuery 语法来说,缩进不会那么糟糕.但这需要您编写自定义 javascript 缩进文件.此外,您必须编辑 html 缩进文件,以免将 cindent 用于带有 javascript 内容的脚本标签.

If you handle that case I'd imagine the indent wouldn't be so awful for the jQuery syntax. But this would require you writing a custom javascript indent file. Also, you'd have to edit the html indent file to not use cindent for script tags with javascript content.

我认为没有人成功为 javascript 创建了与 jquery/prototype 兼容的缩进文件.现有的 javascript 缩进脚本都有缺陷.

I don't think anyone has successfully created a jquery/prototype compatible indent file for javascript. The existing javascript indent scripts are all flawed.

这篇关于如何在 Vim 中格式化 JS 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆