TypeScript/Express環境でローカルサーバを立て、Hello Worldを出力したい。
私自身はReact内で多少TypeScript触ってみた程度ですが、TypeScriptをこれから勉強する人の最初の一歩目を共に歩んでいければなと思います。
環境
npm: 6.14.X
node: 14.13.X
npx: 6.14.X
プロジェクトの作成
$ mkdir ts-app
$ cd ts-app
$ npm init -y
- 作業ディレクトリを作成し、移動します。
- そのディレクトリ内でnpm initとコマンドを打つことで、このディレクトリをnpmの管理下に置くということになります。
- lsコマンドでディレクトリ内を確認すると、package.jsonというファイルが作られていることを確認できるかと思います。
必要なパッケージのインストール
$ npm install --save typescript express
- TypeScriptとExpressをインストールします。
- package.jsonをみればバージョンの確認などができます。
- 私の環境では以下のようになりました。
- "express": "^4.17.1",
- "typescript": "^4.0.3"
TypeScriptが使える環境にする
$npx tsc --init
- 上記のコマンドを入力後lsコマンドを打てば、tsconfig.jsonというファイルが作られたことを確認できるかと思います。
※ typescriptをグローバルインストールしていればtsc --init
のコマンド入力でも同様の結果が得られます。私の場合はグローバルにインストールしてあるtypescriptと作業ディレクトリ内のtypescriptでのバージョン差異が起こらないように上のコマンドで実施しています。
tsconfig.jsonを編集
新たに作られたtsconfig.jsonを見てみます。
{"compilerOptions":{/*Visithttps://aka.ms/tsconfig.jsontoreadmoreaboutthisfile*//*BasicOptions*///"incremental":true,/*Enableincrementalcompilation*/"target":"es5",/*SpecifyECMAScripttargetversion:'ES3'(default),'ES5','ES2015','ES2016','ES2017','ES2018','ES2019','ES2020',or'ESNEXT'.*/"module":"commonjs",/*Specifymodulecodegeneration:'none','commonjs','amd','system','umd','es2015','es2020',or'ESNext'.*///"lib":[],/*Specifylibraryfilestobeincludedinthecompilation.*///"allowJs":true,/*Allowjavascriptfilestobecompiled.*///"checkJs":true,/*Reporterrorsin.jsfiles.*///"jsx":"preserve",/*SpecifyJSXcodegeneration:'preserve','react-native',or'react'.*///"declaration":true,/*Generatescorresponding'.d.ts'file.*///"declarationMap":true,/*Generatesasourcemapforeachcorresponding'.d.ts'file.*///"sourceMap":true,/*Generatescorresponding'.map'file.*///"outFile":"./",/*Concatenateandemitoutputtosinglefile.*///"outDir":"./",/*Redirectoutputstructuretothedirectory.*///"rootDir":"./",/*Specifytherootdirectoryofinputfiles.Usetocontroltheoutputdirectorystructurewith--outDir.*///"composite":true,/*Enableprojectcompilation*///"tsBuildInfoFile":"./",/*Specifyfiletostoreincrementalcompilationinformation*///"removeComments":true,/*Donotemitcommentstooutput.*///"noEmit":true,/*Donotemitoutputs.*///"importHelpers":true,/*Importemithelpersfrom'tslib'.*///"downlevelIteration":true,/*Providefullsupportforiterablesin'for-of',spread,anddestructuringwhentargeting'ES5'or'ES3'.*///"isolatedModules":true,/*Transpileeachfileasaseparatemodule(similarto'ts.transpileModule').*//*StrictType-CheckingOptions*/"strict":true,/*Enableallstricttype-checkingoptions.*///"noImplicitAny":true,/*Raiseerroronexpressionsanddeclarationswithanimplied'any'type.*///"strictNullChecks":true,/*Enablestrictnullchecks.*///"strictFunctionTypes":true,/*Enablestrictcheckingoffunctiontypes.*///"strictBindCallApply":true,/*Enablestrict'bind','call',and'apply'methodsonfunctions.*///"strictPropertyInitialization":true,/*Enablestrictcheckingofpropertyinitializationinclasses.*///"noImplicitThis":true,/*Raiseerroron'this'expressionswithanimplied'any'type.*///"alwaysStrict":true,/*Parseinstrictmodeandemit"use strict"foreachsourcefile.*//*AdditionalChecks*///"noUnusedLocals":true,/*Reporterrorsonunusedlocals.*///"noUnusedParameters":true,/*Reporterrorsonunusedparameters.*///"noImplicitReturns":true,/*Reporterrorwhennotallcodepathsinfunctionreturnavalue.*///"noFallthroughCasesInSwitch":true,/*Reporterrorsforfallthroughcasesinswitchstatement.*//*ModuleResolutionOptions*///"moduleResolution":"node",/*Specifymoduleresolutionstrategy:'node'(Node.js)or'classic'(TypeScriptpre-1.6).*///"baseUrl":"./",/*Basedirectorytoresolvenon-absolutemodulenames.*///"paths":{},/*Aseriesofentrieswhichre-mapimportstolookuplocationsrelativetothe'baseUrl'.*///"rootDirs":[],/*Listofrootfolderswhosecombinedcontentrepresentsthestructureoftheprojectatruntime.*///"typeRoots":[],/*Listoffolderstoincludetypedefinitionsfrom.*///"types":[],/*Typedeclarationfilestobeincludedincompilation.*///"allowSyntheticDefaultImports":true,/*Allowdefaultimportsfrommoduleswithnodefaultexport.Thisdoesnotaffectcodeemit,justtypechecking.*/"esModuleInterop":true,/*EnablesemitinteroperabilitybetweenCommonJSandESModulesviacreationofnamespaceobjectsforallimports.Implies'allowSyntheticDefaultImports'.*///"preserveSymlinks":true,/*Donotresolvetherealpathofsymlinks.*///"allowUmdGlobalAccess":true,/*AllowaccessingUMDglobalsfrommodules.*//*SourceMapOptions*///"sourceRoot":"",/*SpecifythelocationwheredebuggershouldlocateTypeScriptfilesinsteadofsourcelocations.*///"mapRoot":"",/*Specifythelocationwheredebuggershouldlocatemapfilesinsteadofgeneratedlocations.*///"inlineSourceMap":true,/*Emitasinglefilewithsourcemapsinsteadofhavingaseparatefile.*///"inlineSources":true,/*Emitthesourcealongsidethesourcemapswithinasinglefile;requires'--inlineSourceMap'or'--sourceMap'tobeset.*//*ExperimentalOptions*///"experimentalDecorators":true,/*EnablesexperimentalsupportforES7decorators.*///"emitDecoratorMetadata":true,/*Enablesexperimentalsupportforemittingtypemetadatafordecorators.*//*AdvancedOptions*/"skipLibCheck":true,/*Skiptypecheckingofdeclarationfiles.*/"forceConsistentCasingInFileNames":true/*Disallowinconsistently-casedreferencestothesamefile.*/}}
どうやらいろいろな設定が書かれていてコメントアウトされているようです。。
今回は最低限必要な箇所だけコメントアウトし、必要に応じて編集していきます。
- 9行目の"allowJs" →コメントアウトを外す
- 17行目の"outDir" →コメントアウトを外し、
"outDir": "./dist",
に変更 - 18行目の"rootDir" →コメントアウトを外し、
"rootDir": "./app",
に変更
これで一通りの設定は終了です。
それでは実際にTypeScriptでコードを書いてJavaScriptにコンパイルしてみます。
ファイル作成
- TypeScriptを書くappディレクトリと、コンパイル時にJavaScriptが作られるdistディレクトリを作成し、app.tsファイルを作成します。
$ mkdir app dist
$ touch app/app.ts
app.ts(app.js)の内容としては、localhost:3000にサーバを立て、ブラウザでアクセスすると"{ "message": "Hello World!!" }"というjson形式の文字列が参照できる画面が表示できるようになります。
importexpressfrom'express';constapp=express();app.get('/',(req,res)=>{res.json({"message":"Hello World!!"});});app.listen(3000);
この状態だと1行目の"express"のところでエラーになるかと思います。
VSCodeの場合カーソルを合わせるとエラーの内容が表示されるので見てると、モジュール 'express' の宣言ファイルが見つかりませんでした。
となっているのでexpressの型定義ファイルをインストールします。
$ npm install --save-dev @types/express
エラーが消えたのでコンパイルしていきます。
JavaScriptへのコンパイル
$ npx tsc
このコマンドを入力すると、distディレクトリ内にapp.jsが作られます。
tsconfig.jsonの"outDir"に指定したディレクトリに作られるのです。
watchモード
$ npx tsc --watch
このコマンドを使えばtsファイルが変更されるたびにコンパイルされるようになります。
ctr + C でwatchモードから抜けられます。
サーバを立てる
$ node dist/app.js
このコマンドでapp.jsに指定してあるポートでサーバが立ち上がります。
今回は3000ですので、http://localhost:3000にブラウザでアクセスしてみると、
上手くいきました!
最後に
最後まで読んでいただきまして誠にありがとうございます!
これからTypeScriptでたくさんコードを書いていきたいと思っております。
この記事の内容で、ここ違うよなどの箇所があればバンバン突っ込んでいただけますと幸いでございます!