假设我有简单的记录器:
void main() {
var logger = new MyLogger();
logger.log("hello Dart");
}
我希望此代码在开发模式(VM检查模式)下运行,但我不希望它在我的生产代码中。而且我想用dart2js编译器“树摇”。有一些标准的方法吗?
你可以将代码嵌入到assert
中。在生产代码中忽略断言,当pub build
在release
模式下运行时,我肯定不会为JS构建。
class X {
X() {
print('x created');
}
void log(String m) {
print(m);
}
}
bool log(String m) {
new X()..log(m);
return true;
}
void main() {
assert(() {
new X()..log('in Assert');
return true;
});
assert(() => log('in Assert')); // use a wrapper function
}
当您创建一个返回true
的包装器方法时,您不必每次都显式地执行它。
你也可以看看这个问题How to achieve precompiler directive like functionality
我把@GünterZöchbauer“断言技巧”放在工厂构造函数中:
class _ProductionPlug implements DebugClass{
const _ProductionPlug();
noSuchMethod(_) {} //do nothing
}
class DebugClass{
static final DebugClass _plug = const _ProductionPlug();
log(msg){print(msg);}
DebugClass._(){}
factory DebugClass(){
DebugClass instance;
assert((){
instance = new DebugClass._();
return true;
});
return instance != null ? instance : _plug;
}
}
void main() {
print("hello");
new DebugClass()
..log("debugging");
}
这种方式没什么可说的。