Node.js + TypeScript2024/05/31 |
|
Node.js を TypeScript で利用できるよう設定します。 |
|
| [1] | |
| [2] | 任意の一般ユーザーで、任意のプロジェクトを TypeScript 環境に設定します。 |
|
# 依存関係の定義ファイル package.json 生成 ubuntu@dlp:~/testproject$ npm init -y
Wrote to /home/ubuntu/testproject/package.json:
{
"name": "testproject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
# TypeScript インストール ubuntu@dlp:~/testproject$ npm install typescript ts-node added 20 packages, and audited 21 packages in 3s found 0 vulnerabilities # Node.js の型宣言ファイル インストール ubuntu@dlp:~/testproject$ npm install @types/node up to date, audited 21 packages in 368ms found 0 vulnerabilities # 設定ファイル tsconfig.json を生成 ubuntu@dlp:~/testproject$ npx tsc --init --module commonjs Created a new tsconfig.json with: target: es2016 module: commonjs strict: true esModuleInterop: true skipLibCheck: true forceConsistentCasingInFileNames: true You can learn more at https://aka.ms/tsconfig # 以下の内容で tsconfig.json が生成される ubuntu@dlp:~/testproject$ grep -v -E "^ */|^$" tsconfig.json
{
"compilerOptions": {
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"module": "commonjs", /* Specify what module code is generated. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
# テストアプリを作成して動作確認 ubuntu@dlp:~/testproject$ mkdir src
ubuntu@dlp:~/testproject$
vi src/test-app.ts
import * as http from "http";
import * as os from 'os';
const hostname = os.hostname();
const port = 3000;
const server = http.createServer((req, res) =>
{
res.write("Hello TypeScript World on Node.js!\n");
res.end();
}
);
server.listen(port);
console.log(`http://${hostname}:${port}`);
./node_modules/.bin/ts-node src/test-app.ts http://dlp.srv.world:3000 |
| 任意のクライアントコンピューターで表示された URL に Web アクセスして、以下のようなページが表示されれば OK です。 |
|
| Sponsored Link |
|
|