关于前端:使用Rollupjs来压缩打包NodejsTS项目

6次阅读

共计 1129 个字符,预计需要花费 3 分钟才能阅读完成。

0. 写在后面

  • 失常状况下应用 tscTS我的项目转化为 JS,然而因为没有应用打包工具,所以往往体积较大,本教程应用Rollup.js 来压缩 tsc 后的 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-typescript2:让 rollup 能够看懂 TS 代码

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导入前,应用 tsc 编译后的大小是106KB

Rollup.js导入后大小为12.2KB,大幅压缩了体积

正文完
 0