coffeescript多行字符串编译成多行字符串

iLe*_*ing 47 coffeescript

怎么来这个字符串

"answer 
 to life 
 the universe 
 and everything
 is
 #{40+2}
"
Run Code Online (Sandbox Code Playgroud)

汇编成

"  answer   to life   the universe   and everything  is  " + (40 + 2) + "";
Run Code Online (Sandbox Code Playgroud)

我如何强制coffescript保持多线(保持字符串插值完整):

 "answer \ 
 to life \
 the universe \
 and everything \
 is \
 "+(40+2)
Run Code Online (Sandbox Code Playgroud)

nzi*_*nab 75

尝试使用heredoc语法:

myString = """
answer
to life
the universe
and everything
is
#{40+2}
"""
Run Code Online (Sandbox Code Playgroud)

这会转换为这个javascript:

var myString;

myString = "answer\nto life\nthe universe\nand everything\nis\n" + (40 + 2);
Run Code Online (Sandbox Code Playgroud)

实际上没有任何意义让它实际上是在视觉上编译的javascript中的换行符,是吗?

  • @Agzam:你为什么关心生成的JavaScript是什么样的?这些东西不适合人类消费. (7认同)
  • 当你将javascript转换为coffeescript时,生成的编译js几乎看起来都不一样 - 尝试区分它们是徒劳的.同时将js逐字复制到coffeescript中通常只会导致糟糕的coffeescript.你通常可以用咖啡更优雅地做事.如果您真的想将遗留的js转换为咖啡馆(并且不想只使用'适当的'coffeescript技术),您可以使用http://js2coffee.org/之类的工具.我不确定这与XML字符串有什么关系. (2认同)

Han*_*ack 20

我同意在定义长字符串时能够保留缩进很好.您可以像在javascript中一样在coffeescript中使用字符串添加效果:

myVeryLongString = 'I can only fit fifty-nine characters into this string ' +
                   'without exceeding eighty characters on the line, so I use ' +
                   'string addition to make it a little nicer looking.'
Run Code Online (Sandbox Code Playgroud)

评估为

'I can only fit fifty-nine characters into this string without exceeding eighty characters, so I use string addition to make it a little nicer looking.'
Run Code Online (Sandbox Code Playgroud)