LoginSignup
0
0

More than 1 year has passed since last update.

Rollup.jsによってNode.js/TSプロジェクトをバンドルと圧縮

Posted at

0.初めに

  • 普段、 tsc を使って TS プロジェクトを JS に変換しますが、バンドルツールを使わないと、変換した後のサイズが大きくなってしまうことが多いです。この記事はRollup.jsを使って、バンドルと圧縮を実装します
  • この記事はTSによる開発したNode.jsプロジェクトに基づいて展開します

1.インストール

まずは、Rollup.jsをインストール
公式サイト

yarn add -D rollup

Rollup.jsのプラグインをインストール

yarn add -D @rollup/plugin-commonjs rollup-plugin-terser rollup-plugin-typescript2

プラグイン説明

  • @rollup/plugin-commonjs:プロジェクトが使用する依存関係をrollupに伝えます
  • rollup-plugin-terser:コードを圧縮します
  • rollup-plugin-typescript2rollupTS コードを理解させます

2.設定ファイル

rollup.config.jsファイルを新規作成、ルールを書く

// インポート
const { terser } = require('rollup-plugin-terser')
const commonjs = require('@rollup/plugin-commonjs')
const typescript = require('rollup-plugin-typescript2')

// tsconfig.jsonのマージオプション
// 一般に、デフォルトとしてプロジェクトのtsconfig.jsonを使う
// 個別の項目を修正したかったら、ここでマージできます
const override = { compilerOptions: { module: 'ESNext' } }

module.exports = {
  // プロジェクトの入口
  input: 'src/app.ts',

  // バンドル、出口の設定
  output: {
    file: 'dist/app.min.js',
    format: 'cjs',
    sourcemap: true,
    exports: 'default',
  },

  // プラグイン
  // ご注意!ここでプラグインは順番がある!
  // 最初にtsをjsにコンパイルし、次に依存関係を探し、最後に圧縮する
  plugins: [typescript({ tsconfig: './tsconfig.json', tsconfigOverride: override }), commonjs(), terser()],
}

3.package.json編集

package.jsonファイルで追加
-cの意味は:設定ファイルを使て実行

 "rollup:build": "rollup -c",

4.使用

rollup:buildを実行します

yarn rollup:build

5.検証

Rollup.js使用前、サイズは106KB

6.jpg

Rollup.js使用後、サイズは12.2KB、ボリュームを大幅に削減しました

7.jpg

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