LoginSignup
2
1

More than 3 years have passed since last update.

typescriptから直接bundle.jsを作成する方法

Posted at

本記事ではtypescriptから直接bundle.jsを作成する方法について書いていきます。

<今までのbundle.jsの作成方法>
1.tsファイルをコンパイルしてjsファイルを作成
2.jsファイルをbundleしbundle.jsを作成

この流れが面倒なので直接やってしまおう。

1.ts-loaderをインストールする

npm install --save-dev ts-loader typescript

2.webpackの設定ファイルに記述

webpack.config.jsにどのファイルにts-loaderを実行するかを記述する。

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

module.exports = {
  entry: './src/main.ts',  //最初に読み込ませるファイルもtsファイルに変更

  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  devtool: 'inline-source-map',

  module: {
    rules: [{
      test: /\.ts$/,  //どういうファイルに対して
      use: 'ts-loader',  //何をするか
      exclude: /node_modules/   //このファイルは例外
    }]
  }
}

3.buildしてみる

1.以下のコマンド実行。
npm run build

あれ、エラーだけど、、、、
ERROR in ./src/main.ts
Module not found: Error: Can't resolve './foods.js' in '/Users/*****/*****/******/src'
@ ./src/main.ts 1:0-35 2:0-5

ここでのエラーで原因は、main.tsの中でjsファイルをインポートしようとしているため。

main.ts
import { Foods } from "./foods.js";

Foods.getInstance();

そしたらfoods.tsに書き換えればいいんじゃない?
スクリーンショット 2020-07-07 15.23.58.png

それでもエラーが出てしまいます。

しかし、Webpackを使用する場合は拡張子は.tsで正解なんです!

でもエラーが出ているままって気持ち悪いですよね。。。

こうすることで解決できます!

1.importもとの拡張子を消しちゃいます。
スクリーンショット 2020-07-07 15.28.53.png
※このままだとbuild時にエラーになります

2.webpackの設定ファイルに以下を記述します。

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

module.exports = {
  entry: './src/main.ts',

  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  devtool: 'inline-source-map',

  module: {
    rules: [{
      test: /\.ts$/,
      use: 'ts-loader',
      exclude: /node_modules/
    }]
  }
--------ここから--------------------
  resolve: {
    extensions: ['.ts','.js']
  }
}

これを書くことで拡張子がなくてもOK。

この記述でインポートしようとした時に拡張子がなかったら左から調べてくれるようになります。

Webpackって本当に便利ですね。。。

3.再度buildしてみる

以下のコマンド実行。
npm run build

今回は無事にエラーなくbundle.jsが作成されましたね!!!

以上になります。

2
1
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
2
1