1

我今天刚开始使用 sweet.js,所以有些问题可能很容易解决......

我想从我的生产版本的源中删除日志语句。sweet.js 似乎足够灵活来做到这一点。

有多种日志语句和限制:

  • console.log( "wow");应该被删除,而console.warn( "wow");因此应该保持不变。

  • this.log( "wow");也应该删除

  • 在像这样的陈述中this.assert(foo, "foo is undefined").log( "object created");,应该去掉部分。this.assert(foo, "foo is undefined").log( "object created").flush();.log( ...)

我当前的 sweet.js 宏包括示例什么工作和什么不工作:

macro console {
    rule { .log( $args (,) ...); } => { 
        // was removed
    }
    rule { _ } => { ... }
}

macro this {
    rule { .log( $args (,) ...); } => { 
        // was removed
    }
    rule { _ } => { ... }
}

macro this {
    rule { .log( $args (,) ...); } => { 
        // was removed
    }
    rule { _ } => { ... }
}

    // works
console.log( "wow");

    // works
console
.log
( "wow")
;

    // works partially -> "console." is missing before "warn" : 
    // outputs 'warn("wow");' instead of 'console.warn("Wow");'
console.warn("wow")

    // doesnt work yet
    // should output 'this.assert(foo, "foo is undefined");'
this.assert(foo, "foo is undefined").log( "object created");

    // doesnt work yet
    // should output 'this.assert(foo, "foo is undefined").flush();' 
this.assert(foo, "foo is undefined").log( "object created").flush();

你可以在这里玩:sweetjs editor contains this example

欢迎任何帮助:-)

4

1 回答 1

2
macro console {
  case { $console .$method( $args ... ) } => {
    return #{
      // was removed
    }
  }
}

macro log {
  case infix { . | $log ( $args ... ) } => {
    return #{
      // was removed
    }
  }
}

第二个是中缀宏,左右两边用 . 隔开|
不需要匹配分号。

但是上面的宏也删除了所有的warn,errortime。所以我把它改写成这个宏,它符合问题中的所有条件:

macro log {
  case infix { console . | $log ( $args ... ) } => {
    return #{
      // was removed
    }
  }
  case infix { . | $log ( $args ... ) } => {
    return #{
      // was removed
    }
  }
}
于 2014-09-18T23:45:27.887 回答