這樣看來ES6的多行字符模板可能就不需要了……
通過這個你可以整段整段地在JS中寫HTML、SQL了。
示例
之前你得這樣寫
var str = '' +
'<!doctype html>' +
'<html>' +
' <body>' +
' <h1>❤ unicorns</h1>' +
' </body>' +
'</html>' +
'';
寫起來太復雜
或者這樣寫
var str = '\
<!doctype html>\
<html>\
<body>\
<h1>❤ unicorns</h1> \
</body> \
</html>';
限制很多,你不能使用Windows的換行符,"\" 必須在最后;
現在你可以這樣寫
var str = multiline(function(){/*
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/});
原理
非常簡單:
1. 在一個function中寫上一段多行注釋
2. 將此function toString()
3. 將多行注釋內容用正則匹配出來
如下所示:
var str = (function(){/*
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/});
str.toString().match(/\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//);
整個源碼壓縮后可能不足1K。
防壓縮?
注釋被壓縮工具去掉了怎么辦?
- uglify: 使用 /*@preserve 代替 /* 即可
- Closure Compiler(Google): 使用 /*@preserve 代替 /*
- YUI Compressor: 使用 /*! 代替 /*
所以最終版本是這個樣子的:
var str = multiline(function(){/*!@preserve
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/console.log});
