こんにちは。KOUKIです。
最近、TypeScriptを学び始めました。
TypeScriptは、JavaScriptを型付できる便利なもので、学んでおいて損はありません。
今日は、TypeScriptをWebpackで使う方法を記事にします。
<目次>
Webpackとは
Webpackは、複数のファイルをバンドル、つまり「一つにまとめる」ことができるツールです。
また、ビルド自動化ツールでもあります。
-
バンドルの生成によりHTTPリクエストを少なくできる
-
コードを最適化するため、容量を縮小できる
-
ビルドステップを簡単にカスタマイズできる
Webpackの設定
前提条件
Nodejsが必要なので、ダウンロードしてください。
私は、以下のバージョンのNodejsをインストールしています。
1 2 3 4 |
$ npm -v 6.14.5 $ node -v v12.1.0 |
プロジェクトの作成
作業ディレクトリ(プロジェクト)を作成します。
1 2 |
mkdir typescript-with-webpack cd typescript-with-webpack |
NPMパッケージ初期化
以下のコマンドで、初期化処理を行います。
1 2 3 4 |
npm init -y ls package.json |
初期化に成功するとpackage.jsonが作成されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// package.jsonの中身 { "name": "typescript-with-webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" } |
Webpackの必須モジュール追加
先ほど作成したpackage.jsonにWebpackに必要なモジュールを追加します。
1 2 |
npm install --save-dev webpack webpack-cli webpack-dev-server npm install --save-dev typescript ts-loader |
インストールに成功すると、package.jsonが以下のように変わっているはずです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
{ "name": "typescript-with-webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "ts-loader": "^8.0.1", "typescript": "^3.9.7", "webpack": "^4.43.0", "webpack-cli": "^3.3.12", "webpack-dev-server": "^3.11.0" } } |
追加したモジュールについて、補足を書いておきます。
モジュール名 | 説明 |
---|---|
webpack | webpack本体。複数のファイルを一つにバンドルする |
webpack-cli | webpackのコマンドをプロジェクトで実行する |
webpack-dev-server | 開発用のwebサーバー |
typescript | typescriptモジュール |
ts-loader | webpackがTypeScriptを変換するためのローダー |
TypeScriptの設定ファイルの作成
以下のコマンドで、TypeScriptの設定ファイルを作成してください。
1 2 3 |
tsc --init message TS6071: Successfully created a tsconfig.json file. |
TypeScriptの設定ファイルの変更
TypeScriptの設定ファイルを下記のようにします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
{ "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ "module": "ES2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ "lib": [ "DOM", "ES6", "DOM.Iterable", "ScriptHost" ], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ // "declaration": true, /* Generates corresponding '.d.ts' file. */ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ "outDir": "./dist", /* Redirect output structure to the directory. */ // "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ "noEmitOnError": true, /* Strict Type-Checking Options */ "strict": true, /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ "noUnusedLocals": true, /* Report errors on unused locals. */ "noUnusedParameters": true, /* Report errors on unused parameters. */ "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ /* Advanced Options */ "skipLibCheck": true, /* Skip type checking of declaration files. */ "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ }, "exclude": ["node_modules"] /* would be default */ } |
webpack.config.jsファイルの作成
webpackの設定ファイルをtsconfig.jsonと同階層に作成します。
1 2 3 4 5 6 7 8 9 |
touch webpack.config.js $ tree -L 1 typescript-with-webpack ├── node_modules ├── package-lock.json ├── package.json ├── tsconfig.json └── webpack.config.js |
尚、ファイル名は、「webpack.config.js」でなければなりません。
webpack.config.jsの設定
webpackの設定を以下のようにします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// pathはNodejsをインストールする時についてくるコアモジュール const path = require('path'); module.exports = { // プロジェクト全体のエントリポイント(アプリケーションが最初に起動するところ) entry: './src/app.ts', output: { // webpackがバンドルする名前を指定する filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), // tsconfig.jsonのoutDir設定と同じ場所を指定する 接待パスを指定する必要がある __dirnameはファイルが設置されているフォルダの絶対パスを取得する }, devtool: 'inline-source-map', // ソースマップの生成 // javascriptのオブジェクトを取得 // entryポイントに設定されているファイルから依存関係にあるモジュール情報を全て取得 module: { rules: [ { test: /\.ts$/, // .tsの拡張子に対して、ルールを適用する use: 'ts-loader', exclude: /node_modules/ // node_modulesは対象外 } ] }, // インポートされたモジュールをどの様に解決するか指定する resolve: { extensions: ['.ts', '.js'] // ts/jsのファイルを探し出して、最終的に一つのファイルにする } }; |
公式にも詳しく書いてあります。
Webpackの実行
Webpackを実行するために、package.jsonのscriptsにbuildコマンドを追加します。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ "name": "typescript-with-webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack" // 追加 }, ... } } |
ビルド用のファイルを作成します。
1 2 3 4 5 6 7 8 9 10 11 |
mkdir src touch src/app.ts tree . ├── node_modules ├── package-lock.json ├── package.json ├── src/app.ts ├── tsconfig.json └── webpack.config.js |
1 2 |
// app.ts console.log("test"); |
準備が整ったので、webpackを実行してみましょう。
1 |
npm run build |
コマンド実行に成功するとdistフォルダが作成されます。
webpack-dev-serverの設定
最後に、webpackから開発用のwebサーバーを起動できるようにします。
package.jsonのscriptsに以下の設定を追加してください。
1 2 3 4 5 6 7 8 9 10 11 |
{ ... "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server", // 追加 "build": "webpack" }, ... } } |
startコマンドを追加しました。
以下のように実行します。
1 |
npm run start |
このコマンドの実行に成功すると「localhost:8080」にて、プロジェクトがスタートします。
確認のために、index.htmlを作成しましょう。
1 2 3 4 5 6 7 8 9 10 |
touch index.html typescript-with-webpack ├── dist ├── index.html ├── node_modules ├── package-lock.json ├── package.json ├── src ├── tsconfig.json └── webpack.config.js |
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>TypeScript Test</title> <script src="dist/bundle.js"></script> </head> <body> Here is TypeScript Testing Field. </body> </html> |
ブラウザから「localhost:8080」にアクセスします。

問題なく表示されているように見えますが、webpack.config.jsに追加の設定が必要です。
1 2 3 4 5 6 7 8 9 10 |
module.exports = { // プロジェクト全体のエントリポイント(アプリケーションが最初に起動するところ) entry: './src/app.ts', output: { // webpackがバンドルする名前を指定する filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), // tsconfig.jsonのoutDir設定と同じ場所を指定する 接待パスを指定する必要がある __dirnameはファイルが設置されているフォルダの絶対パスを取得する publicPath: 'dist' // webpack-dev-serverがdistフォルダを参照するための設定 }, } |
publicPathを追加しました。
webpack-dev-serverは、ファイルの変更等があればホットリロード(自動リロード)を走らせますが、デフォルトの設定では変更内容を反映しません。
そのため、上記の設定が必要になります。
開発モードの設定
webpack.config.jsに以下の設定を行います。
1 2 3 4 5 |
module.exports = { mode: 'development', // ファイル縮小などを行わない、わかりやすいエラーメッセージなどが表示される ... } |
これは、開発中には設定しておきたいものです。
本番モードの設定
本番モードの設定もみてみましょう。
次のファイルを作成してください。
1 |
touch webpack.config.prod.js |
上記のファイル名は任意のものです。
また、distフォルダ配下のファイルを削除するパッケージを追加しておきましょう。
1 |
npm install --save-dev clean-webpack-plugin |
設定ファイルの中身は、以下のようにします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// pathはNodejsをインストールする時についてくるコアモジュール const path = require('path'); const CleanPlugin = require('clean-webpack-plugin'); module.exports = { mode: 'production', entry: './src/app.ts', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), }, devtool: 'none', module: { rules: [ { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/ } ] }, resolve: { extensions: ['.ts', '.js'] }, // プロジェクト全体に適用されるプラグインを設定する plugins: [ // distフォルダの中身をクリアする new CleanPlugin.CleanWebpackPlugin(), ] }; |
package.jsonのbuildコマンドを修正します。
1 2 3 4 5 6 7 8 9 10 |
{ ... "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server", "build": "webpack --config webpack.config.prod.js", "build-dev": "webpack" }, ... } |
webpackは、デフォルトでは、webpack.config.jsファイルを読み込みますが、上記の様にconfigオプションにファイルを指定するとその設定ファイルを読み込むことが可能です。
以下のコマンドで、ビルドをしましょう。
1 |
npm run build |
おわりに
Webpackは、モジュールバンドラツールのうち、もっとも重要なツールだと思います。
プロジェクト規模が大きくなるとかなり重宝するはずです。
自己学習においてもガンガン取り入れるべきものだと思いますので、この記事が参考になればあ幸いです^^
関連記事
参考
設定ファイル
本記事で作成した設定ファイルをいかに貼り付けておきます。
package.json
package.jsonを
すると依存関係のモジュールをインストールしてくれるので、便利です。npm install
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
{ "name": "typescript-with-webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server", "build": "webpack --config webpack.config.prod.js", "build-dev": "webpack" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "clean-webpack-plugin": "^3.0.0", "ts-loader": "^8.0.1", "typescript": "^3.9.7", "webpack": "^4.43.0", "webpack-cli": "^3.3.12", "webpack-dev-server": "^3.11.0" }, "dependencies": {} } |
webpack.config.prod.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// pathはNodejsをインストールする時についてくるコアモジュール const path = require('path'); const CleanPlugin = require('clean-webpack-plugin'); module.exports = { mode: 'production', entry: './src/app.ts', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), }, devtool: 'none', module: { rules: [ { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/ } ] }, resolve: { extensions: ['.ts', '.js'] }, // プロジェクト全体に適用されるプラグインを設定する plugins: [ // distフォルダの中身をクリアする new CleanPlugin.CleanWebpackPlugin(), ] }; |
webpack.config.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// pathはNodejsをインストールする時についてくるコアモジュール const path = require('path'); module.exports = { mode: 'development', // ファイル縮小などを行わない、わかりやすいエラーメッセージなどが表示される // プロジェクト全体のエントリポイント(アプリケーションが最初に起動するところ) entry: './src/app.ts', output: { // webpackがバンドルする名前を指定する filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), // tsconfig.jsonのoutDir設定と同じ場所を指定する 接待パスを指定する必要がある __dirnameはファイルが設置されているフォルダの絶対パスを取得する publicPath: 'dist' // webpack-dev-serverがdistフォルダを参照するための設定 }, devtool: 'inline-source-map', // ソースマップの生成 // javascriptのオブジェクトを取得 // entryポイントに設定されているファイルから依存関係にあるモジュール情報を全て取得 module: { rules: [ { test: /\.ts$/, // .tsの拡張子に対して、ルールを適用する use: 'ts-loader', exclude: /node_modules/ // node_modulesは対象外 } ] }, // インポートされたモジュールをどの様に解決するか指定する resolve: { extensions: ['.ts', '.js'] // ts/jsのファイルを探し出して、最終的に一つのファイルにする } }; |
tsconfig.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
{ "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ "module": "ES2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ "lib": [ "DOM", "ES6", "DOM.Iterable", "ScriptHost" ], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ // "declaration": true, /* Generates corresponding '.d.ts' file. */ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ "outDir": "./dist", /* Redirect output structure to the directory. */ // "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ "noEmitOnError": true, /* Strict Type-Checking Options */ "strict": true, /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ "noUnusedLocals": true, /* Report errors on unused locals. */ "noUnusedParameters": true, /* Report errors on unused parameters. */ "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ /* Advanced Options */ "skipLibCheck": true, /* Skip type checking of declaration files. */ "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ }, "exclude": ["node_modules"] /* would be default */ } |
必須コマンド
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# npm初期化 npm init -y # 必要モジュールのインストール npm install --save-dev webpack webpack-cli webpack-dev-server npm install --save-dev typescript ts-loade npm install --save-dev clean-webpack-plugin # TypeScriptの初期化 tsc --init # webpackの設定ファイルを作成 touch webpack.config.js touch webpack.config.prod.js # ビルド # 本番 npm run build # 開発 npm run build-dev # サーバースタート npm run start |
最近のコメント