LoginSignup
1
1

More than 3 years have passed since last update.

webpack5でTypeScriptで型定義使用してconfigを記述しホットリロードを実現する

Last updated at Posted at 2021-02-21

2021/03/13 修正
ソースマップを作成するための devtool が抜けていたのを追加

サンプル

まずはサンプルを。

import { WebpackOptionsNormalized } from "webpack";

const option: WebpackOptionsNormalized = {
    mode: "development",
    cache: {
        type: "filesystem",
        buildDependencies: {
            config: [__filename]
        }
    },
    devServer: {
        contentBase: "dist",
        open: true
    },
    devtool: 'eval-source-map',
    entry: {
        main: {
            import: ["./src/index.tsx"]
        }
    },
    experiments: {

    },
    externals: {

    },
    externalsPresets: {

    },
    infrastructureLogging: {

    },
    module: {
        defaultRules: [
            "..."
        ],
        generator: {

        },
        parser: {

        },
        rules: [
            {
                test: /\.tsx?$/,
                use: "ts-loader"
            }
        ]
    },
    node: {

    },
    optimization: {

    },
    output: {
        filename: "[name].js",
        path: `${__dirname}/dist`,
    },
    plugins: [],
    resolve: {
        extensions: [".ts", ".tsx", ".js", ".jsx"]
    },
    resolveLoader: {

    },
    snapshot: {

    },
    stats: {

    },
    watchOptions: {

    }
}
};

export default option;

Configuration ではなく WebpackOptionsNormalized を使う

webpack configをTypeScriptで記述する記事を見ると、 webpack.Configuration を使用している場合が多いです。
しかし webpack.Configuration にはホットリロードに必要な devServer が定義されていません。
手っ取り早いのは webpack.Configuration を使用せず型なしのオブジェクトとして記述することですが、それではTypeScriptを使う意味がありません。
そこで devServer が定義されている webpack.WebpackOptionsNormalized を使用します。

WebpackOptionsNormalized は定義が多い

webpack.WebpackOptionsNormalizedwebpack.Configuration と比較すると定義する必要がある項目が多いです。
しかしそのほとんどは空で構いません。

entryの書き方が違う

entry には filename を記述することが多いかと思います。
しかし webpack.WebpackOptionsNormalizedentry には import を記述することが必須となります。
そのため filename ではなく import を記述することになります。

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