LoginSignup
1
0

More than 3 years have passed since last update.

typeScriptにWebpackを使用する

Posted at

※あくまで個人の学習ノートなので参考程度に

1.package.jsonを追加

npm init -y

package.jsonが作成される

2.webpackインストール

npm install --save-dev webpack webpack-cli

node_moduleのフォルダとpackage-lock.jsonが作成される。

※作成されるnode_moduleはgitにpushしない

3.webpack.config.jsをディレクトリに追加

webpack.config.jsはwebpackの設定ファイル

webpack.config.js
const path = require('path'); //requireimportと同じ扱いでpathnodejsがもっているモジュール

module.exports = {
  entry: './dist/main.js', //一番最初に読み込ませるjsファイル

  output: {    //生成したファイルをどこに格納するかを指定
    filename: 'bundle.js', //生成されるファイル名
    path: path.resolve(__dirname, dist), //生成されるファイルの格納ディレクトリ
  }
}

4.bundle.jsを作成

npm run build

bundle.jsが作成される。

5.HTMLファイルの記述変更

jsファイルの読み込み先を先ほど作成したbundle.jsに変更
(bundle.jsに全てのjsファイルのコードがまとまっているため)

index.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
  <script src="dist/bundle.js" defer></script>
</head>

以上で終了。

-----------ここからはやってもやらなくても良い-------------

・sourceマップにjsファイルを表示したい場合

1.現在の状態だと以下のように検証ツール上にはbundle.jsしか表示されていない。
スクリーンショット 2020-07-07 14.32.57.png

2.webpackの設定ファイルにdevtool: 'inline-source-map'と追加する

webpack.config.js
const path = require('path');

module.exports = {
  entry: './dist/main.js',

  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, dist),
  },
  devtool: 'inline-source-map'  //この行を追加
}

3.再度buildすると以下のように変わる
スクリーンショット 2020-07-07 14.39.24.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0