简体   繁体   中英

Keeping indent after compiling from coffeescript to javascript?

I have file app.coffee

angular
  .module('app', [
    'ngAnimate',
    'angular-loading-bar',
    'ui.router',
    'oc.lazyLoad',
    'ui.bootstrap',
    'ngResource'
  ])

When I compile it to javascript it looks like this

// Generated by CoffeeScript 1.10.0
(function() {
  angular.module('app', ['ngAnimate', 'angular-loading-bar', 'ui.router', 'oc.lazyLoad', 'ui.bootstrap', 'ngResource']);

}).call(this);

Is there any way I can keep the indenting?

There is no way to modify the output of the CoffeeScript compiler beyond a few simple options (eg --bare ).

Do you care what the generated assembly code of your C programs looks like? Or the bytecode of your Python programs? Normally you don't, and you only look at it very rarely to debug specific problems. The JavaScript code that CofeeScript generates is the same. Accept that the compiled JS code is not intended for human consumption. Sure, it's formatted in such a way that you can read it to debug problems (which is nice), but that's not the primary concern.


That being said, you can run it through external formatting tools, but how would they distinguish between these two arrays:

angular
  .module('app', [
    'ngAnimate',
    'angular-loading-bar',
    'ui.router',
    'oc.lazyLoad',
    'ui.bootstrap',
    'ngResource'
  ])

one_line_array = ['ngAnimate', 'angular-loading-bar']

There is no way other than taking the JS code and the CoffeeScript code.

If you really want this, you'll need to either modify the CoffeeScript source, or write your own tool which analyses the CofeeScript source and modifies the JavaScript output accordingly. If you print the tokens with coffee --tokens , you get:

[IDENTIFIER angular] [= =] [{ {] [IDENTIFIER module] [: :] [-> ->] [INDENT 2] [OUTDENT 2] [} }] [TERMINATOR \\n] [IDENTIFIER angular] [. .] [IDENTIFIER module] [CALL_START (] [STRING 'app'] [, ,] [[ [] [INDENT 4] [STRING 'ngAnimate'] [, ,] [TERMINATOR \\n] [STRING 'angular-loading-bar'] [, ,] [TERMINATOR \\n] [STRING 'ui.router'] [, ,] [TERMINATOR \\n] [STRING 'oc.lazyLoad'] [, ,] [TERMINATOR \\n] [STRING 'ui.bootstrap'] [, ,] [TERMINATOR \\n] [STRING 'ngResource'] [OUTDENT 4] [] ]] [CALL_END )] [TERMINATOR \\n]

Which does store the newlines as [TERMINATOR \\n] . Writing (and debugging!) a tool which does this is not necessarily easy though, and beyond the scope of a Stack Overflow answer ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM