事前準備
サーバーサイド用のディレクトリを作成します。
$ mkdir server
$ cd server
npmの初期化をします。この後に出てくる質問は全てそのままEnterでOKです。
package.jsonが生成されています。
$ npm init
必要なパッケージをインストールしていきます。
$ npm i cors express
$ npm i -D @types/cors @types/express @types/node ts-loader typescript webpack webpack-cli webpack-node-externals
// Linterを入れる場合
npm i -D @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint eslint-config-prettier eslint-plugin-prettier prettier
TypeScriptの設定
TypeScriptの設定ファイルを生成します。
$ touch tsconfig.json
生成したtsconfig.jsonに下記の内容をコピペします。
tsconfigの各オプションについては。こちらを参考にしてください。
tsconfig.json
{
"compilerOptions": {
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "ES2019",
"lib": [
"ES2019",
"dom"
],
"baseUrl": ".",
"paths": {
"src/*": [
"src/*"
],
},
"outDir": "./dist",
"moduleResolution": "node",
"removeComments": true,
"strict": true,
"noUnusedLocals": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"strictFunctionTypes": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
},
"include": [
"src/**/*",
],
"exclude": [
"node_modules",
],
}
Webpackの設定
TypeScriptをトランスパイルしてJavaScriptに変換するためにWebpackを使います。
まず設定ファイルを生成します。
$ touch webpack.config.js
生成したwebpack.config.jsに下記内容をコピペします。
webpack.config.js
const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
mode: process.env.NODE_ENV || 'development',
entry: './src/index.ts',
target: 'node',
externals: [nodeExternals()],
devtool: 'inline-source-map',
module: {
rules: [
{
loader: 'ts-loader',
test: /\.ts$/,
exclude: [/node_modules/],
options: {
configFile: 'tsconfig.json',
},
},
],
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
alias: {
src: path.resolve(__dirname, 'src'),
mock: path.resolve(__dirname, 'mock'),
},
},
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
},
};
(オプション)Linterの設定
ESLintとPrettierの設定ファイルを生成します
$ touch .eslintrc.json
生成した.eslintrc.jsonに下記の内容をコピペします。
.eslintrc.json
{
"extends": [
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
"prettier/@typescript-eslint"
],
"env": {
"browser": true,
"es6": true,
"node": true
},
"parserOptions": {
"sourceType": "module"
},
"rules": {
"@typescript-eslint/no-var-requires": 0,
"@typescript-eslint/no-empty-interface": 0,
"@typescript-eslint/explicit-function-return-type": 0,
"@typescript-eslint/interface-name-prefix": 0,
"@typescript-eslint/ban-types": 0,
"@typescript-eslint/explicit-module-boundary-types": 0,
"prettier/prettier": ["error", {
"semi": true,
"arrowParens": "always",
"singleQuote": true
}]
}
}
package.jsonにlintのコマンドを追加します。
package.json
...
"scripts": {
"lint": "eslint --ext .js,.ts --ignore-path .gitignore . --fix", // add
"test": "echo \"Error: no test specified\" && exit 1"
},
...
これで概ね準備完了です。