I took some inspiration from Importing lodash into angular2 + typescript application and finally figured out how to import it. No console errors and no compiler errors this time.
First I should mention: when upgrading from typescript 1
to typescript 2
the typings
tool gets deprecated. Instead, npm
package manager is used to install type definitions.
I followed these steps:
npm install debug --save
npm install @types/debug --save
- Mapped debug in
system.config.js
system.config.js:
map: {
'debug': '../node_modules/debug/browser.js',
...
}
- Import in any .ts file you need:
import * as debug from 'debug';
- Optionally, if needed in index.html use:
<script>System.import('debug');</script>
Untill now this should work, however a pesky error persists: GET http://localhost:8002/ms.js 404 (Not Found)
. I fixed this by editing node_modules/debug/debug.js
.
- Replace line 14:
exports.humanize = require('ms');
with exports.humanize = require('node_modules/ms/index');
.
I am not sure what this implies for other use cases of debug
. If you have any suggestions on how to improve this solution so it is not necessary to edit inside node_modules/debug/debug.js
write a comment.
Usage in browser
Preferably in app.component.ts or main.module.ts write:
// Expose debugsApp in window object in order to access it from the console.
// window.debug is already used by chrome.
import * as debug from 'debug';
(<any>window).debugApp = debug; // The typescript way to extend window
In any other .ts file:
import * as Debug from 'debug';
var debug = Debug('app:someModule');
debug('Some message');
Finally in the console type as you need:
// Business as usual
debugApp.enable('*'); // Enable all
debugApp.enable('app'); // Enable app debugger
debugApp.enable('app:*'); // Enable app debuggers if they are namespaced
debugApp.enable('app:someModule'); // Enable someModule
debugApp.disable('*'); // Disable all
EDIT
I had an unexpected issue with this method. I could either load the server path or the frontend path for the debug script. So I had to do another improvisation.
node_modules/debug/debug.js - Line 14
if (typeof process === 'undefined') {
exports.humanize = require('node_modules/ms/index.js');
} else {
exports.humanize = require('ms');
}
This triggers another issue on itself. System.js likes to parse ahead the exports so this leads to abnormal behavior when exports
statement is combined with an if
statement. More details here. Fortunately there is a fix. More details here thanks to @guybedford
In system.config.js add:
System.config({
map: {
ms: '@empty'
}
});
In the end it's a patch-up job, but it works. Hopefully debug authors will suggest a better solution. Until then use this.