備忘録

備忘録

TypeScript+webpack+Node.jsでHelloWorldする方法

Ⅰ. はじめに

タイトルの通り「TypeScript+webpack+Node.jsでHelloWorldする方法」です。

Ⅱ. やり方

1. プロジェクトを作成する
mkdir helloworld
cd helloworld
npm init -y
npm i -D typescript ts-loader webpack webpack-cli webpack-node-externals
npx tsc --init
2. webpack.config.js を作成する

webpack.config.js

const path = require('path')
const nodeExternals = require('webpack-node-externals')

module.exports = {
  mode: 'development',
  // mode: 'production',
  entry: './src/index.ts',
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'dist')
  },
  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', '.js' ]
  }
}
3. package.json に start を追加する
{
  "scripts": {
    "start": "webpack --config webpack.config.js & node dist/index.js"
  }
}
4. サンプルプログラムを書く

src/index.ts

function myFunc(myName: string): string {
  return `hello ${myName}`
}

const myName = 'tanaka'
const str = myFunc(myName)
console.log(str)
5. 実行する
npm run start
6. 実行結果
hello tanaka