[typescript] Typescript&Webpack

Suyeon·2020년 11월 20일
0

Typescript

목록 보기
10/12
post-thumbnail

Sending many http request per each small file takes loading time. It makes your app slow.

  • Check network tab (http request)

Webpack

  • Code bundles, less imports required.
  • Optimized code(minified), less code download.
  • More build tool can be added easily.

Setup

1️⃣ Install
npm install --save-dev webpack webpack-cli webpack-dev-server typescript ts-loader

  • webpack: transform typescript code to javascript code and bundling them.
  • ts-loader: It helps webpack and typescript working together.
  • You don't need file extension when import a module(.js) with webpack.
  • Installing typescript together is recommended for preventing collision of other package's version.

2️⃣ webpack.config.js(development mode, default)

  • Path should be an absolute path.
  • Filename is up to you. (bundle.js)
  • publicPath makes dev-server working(specify the base path for all the assets within your application).
const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/app.ts',
    devServer: {
    contentBase: './dist',
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: 'dist'
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
};

3️⃣ webpack.config.prod.js(production mode)

  • Filename is up to you(webpack.config.prod.js).
  • CleanPlugin removes cached files on dist folder when rebuilding an app in order to keep newest bundled file.
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'),
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  plugins: [new CleanPlugin.CleanWebpackPlugin()],
};

4️⃣ package.json

  • "build": "webpack --config will use chosen file not webpack.config.js when running production mode.
"start": "webpack serve",
"build": "webpack --config webpack.config.prod.js"

5️⃣ index.html
<script type="module" src="dist/bundle.js"></script>

profile
Hello World.

0개의 댓글