参考这个问题,我使用这段代码来查找自定义日志函数调用者的行号:
/**
* eLog - displays calling line number & message & dumps vars as pretty json string
* @param {string} msg - string to display in log message
* @param {any} dispVars - any number of variables (ellipsis , aka Rest parameters) to dump
*/
function eLog(msg:string,...dispVars:any[]){
let caller_line = (new Error).stack.split("n")[4];
console.log(`eLog->Line#${caller_line}->${msg}->`);
console.log(JSON.stringify((new Error).stack.split("n"),null,2));
dispVars.forEach(value => {
console.log(JSON.stringify(value,null,2));
});
}
像这样调用:
eLog("eLog Test",this);
虽然这确实对.js
文件行#进行了适当的转储,但我需要源行#,即.ts
行号。我怎样才能正确地生成它?
整个晚上我都在考虑这个问题,并想出了一个令我满意的函数。谢谢你的帮助-
分离成log.ts
require('source-map-support').install({
environment: 'node'
});
/**
* eLog - displays calling line number & message & dumps vars as pretty json string
* @param {string} msg - string to display in log message
* @param {any} dispVars - any number of variables (ellipsis , aka Rest parameters) to dump
* {@link https://github.com/evanw/node-source-map-support usable by typescript node-source-map-support module}
* {@link https://github.com/mozilla/source-map/ Mozilla source-map library & project}
* {@link http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/ good introduction to sourcemaps}
*/
export function eLog(msg:string,...dispVars:any[]){
/**
* go one line back for the caller
* @type {string}
*/
let stackLine = (new Error).stack.split("n")[2];
/**
* retrieve the file basename & positional data, after the last `/` to the `)`
*/
//
let caller_line = stackLine.slice(stackLine.lastIndexOf('/'),stackLine.lastIndexOf(')'))
/**
* test for no `/` ; if there is no `/` then use filename without a prefixed path
*/
if ( caller_line.length == 0 ) {
caller_line = stackLine.slice(stackLine.lastIndexOf('('),stackLine.lastIndexOf(')'))
}
//
/**
* filename_base - parse out the file basename; remove first `/` char and go to `:`
*/
let filename_base = caller_line.slice(0+1,caller_line.indexOf(':'));
/**
* line_no - parse out the line number ; remove first `:` char and go to 2nd `:`
*/
let line_no = caller_line.slice(caller_line.indexOf(':')+1,caller_line.lastIndexOf(':'));
/**
* line_pos - line positional - from the last `:` to the end of the string
*/
let line_pos = caller_line.slice(caller_line.lastIndexOf(':')+1);
console.log(`eLog called by ${filename_base} on line# ${line_no} @ char# ${line_pos} said:n${msg}`);
// print out the input variables as pretty JSON strings
dispVars.forEach(value => {
console.log(JSON.stringify(value,null,2));
});
}
可以用简单的:
调用eLog("eLog Test",this);
从任何文件,只要函数被加载(如)
import { eLog } from './log'
我希望这能帮助到别人。
欢呼。eric
如何正确生成
)。你的代码相当依赖于用户运行时(例如,在IE中不起作用)。
b。)要使js -> ts工作,您需要源代码地图。让事情变得简单的东西已经不存在了。使用源映射的事实上的原始包是:https://www.npmjs.com/package/source-map