npmパッケージをインストール
$ npm i -S underscore
型宣言をインストール
npm i -S @types/underscore
インポート
import * as _ from "underscore";
Please follow and like us:
$ npm i -S underscore
npm i -S @types/underscore
import * as _ from "underscore";
$ npm i -S log4js @types/log4js
コンソールとファイルに、ログを同時出力。
import { configure, getLogger } from "log4js";
configure({
appenders: {
console: {
type: "console"
},
logfile: { type: "file", filename: "log/app.log" }
},
categories: { default: { appenders: ["console", "logfile"], level: "error" } }
});
const logger = getLogger();
logger.level = "debug";
logger.debug("Some debug messages");
logger.error("aha!");
出力結果
[2019-10-20T10:58:43.835] [DEBUG] default - Some debug messages
[2019-10-20T10:58:43.839] [ERROR] default - aha!
設定を変えると、ログレベルごとに出力先を変えたり、ログの出力のテンプレート(レイアウト)を変更できたりする。
log4jsのドキュメント
https://log4js-node.github.io/log4js-node/
日付の形式について
https://www.npmjs.com/package/date-format
node.jsでアプリケーションをつくるのに、TypeScriptで書いて、Visual Studio Codeを開発環境とする方法を探る
https://qiita.com/notakaos/items/3bbd2293e2ff286d9f49
https://qiita.com/kurogelee/items/cf7954f6c23294600ef2
https://github.com/TypeStrong/ts-node/issues/46#issuecomment-437758378
ここのボイラープレートをテンプレートにすると便利です。必要なnpmパッケージ、設定ファイルがはいっています。git clone
などでローカルに。
https://github.com/notakaos/typescript-node-base
{
"name": "typescript-node-base",
"keywords": [],
"version": "0.1.0",
"main": "dist/index.js",
"scripts": {
"dev": "ts-node ./src/index.ts",
"dev:watch": "ts-node-dev --respawn src/index.ts",
"clean": "rimraf dist/*",
"tsc": "tsc",
"build": "npm-run-all clean tsc",
"start": "node ."
},
"keywords": [],
"author": "YOUR NAME",
"license": "ISC",
"description": "",
"dependencies": {},
"devDependencies": {
"@types/node": "^12.7.4",
"npm-run-all": "^4.1.5",
"rimraf": "^2.7.1",
"ts-node": "^8.3.0",
"ts-node-dev": "^1.0.0-pre.42",
"typescript": "^3.6.2"
}
}
L9: --respawn
を指定することで、サーバ型ではないスクリプトでも、実行後終了せずに待機させ、更新→再読み込み→再起動が可能に。
{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"sourceMap": true,
"outDir": "./dist",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true
},
"include": ["src/**/*"]
}
sourceMap
は有効にしましょう。Debugが効くようになります。
{
"version": "0.2.0",
"configurations": [
{
"name": "ts-node[debug]",
"type": "node",
"request": "launch",
"args": ["${workspaceFolder}/src/index.ts"],
"runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
"sourceMaps": true,
"cwd": "${workspaceRoot}",
"restart": true,
"protocol": "inspector"
}
]
}
L8: 任意のファイルを指定
https://github.com/TypeStrong/ts-node/issues/46#issuecomment-437758378
の投稿が参考になりました。