• Stars
    star
    139
  • Rank 262,954 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 3 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Use SWC with Rollup to transform / minify ESNext and TypeScript code.

rollup-plugin-swc

SWC is an extensible Rust-based platform for the next generation of fast developer tools. This plugin is designed to replace rollup-plugin-typescript2, @rollup/plugin-typescript, @rollup/plugin-babel and rollup-plugin-terser for you.

New: Building library for React Server Component support is added in 0.9.0! 'use client' and 'use server' directives now are handled properly, without triggering rollup warnings. Start using 'use client' and 'use server' in your library by adding two lines in your rollup.config.js

Since 0.9.1 the support for 'use client' and 'use server' has been separated into a standalone rollup plugin rollup-preserve-directives, the previous preserveUseDirective named export is retained for the backward compatibility.

Comparison

sukkaw/rollup-plugin-swc mentaljam/rollup-plugin-swc nicholasxjy/rollup-plugin-swc2 @rollup/plugin-swc
minify your bundle in one pass1 โœ… ๐Ÿ›‘ ๐Ÿ›‘ ๐Ÿ›‘
Standalone swcMinify plugin โœ… ๐Ÿ›‘ ๐Ÿ›‘ ๐Ÿ›‘
Config Intellisense2 โœ… ๐Ÿ›‘ ๐Ÿ›‘ ๐Ÿ›‘
Reads your tsconfig.json and jsconfig.json โœ… ๐Ÿ›‘ ๐Ÿ›‘ ๐Ÿ›‘
ESM export โœ… ๐ŸŸก3 ๐Ÿ›‘ โœ…
TypeScript declarations โœ… โœ… โœ… โœ…
Has testing โœ… ๐Ÿ›‘ ๐Ÿ›‘ โœ…

Install

$ npm i @swc/core rollup-plugin-swc3
# If you prefer yarn
# yarn add @swc/core rollup-plugin-swc3
# If you prefer pnpm
# pnpm add @swc/core rollup-plugin-swc3

Usage

// rollup.config.js
import { swc } from 'rollup-plugin-swc3';

export default {
  input: 'xxxx',
  output: {},
  plugins: [
    swc({
      // All options are optional
      include: /\.[mc]?[jt]sx?$/, // default
      exclude: /node_modules/, // default
      tsconfig: 'tsconfig.json', // default
      // tsconfig: false, // You can also prevent `rollup-plugin-swc` from reading tsconfig.json, see below
      // And add your swc configuration here!
      // "filename" will be ignored since it is handled by rollup
      jsc: {}
    }),
  ];
}

If you want autocompletion in your IDE or type check:

import { swc, defineRollupSwcOption } from 'rollup-plugin-swc3';

export default {
  input: 'xxxx',
  output: {},
  plugins: [
    swc(defineRollupSwcOption({
      // ... There goes the plugin's configuration
    })),
  ];
}

// or
/** @type {import('rollup-plugin-swc3').PluginOptions} */
const swcPluginConfig = {}

exclude

  • Type: string | RegExp | Array<String | RegExp>
  • Default: /node_modules/

A picomatch pattern, or array of patterns, which specifies the files in the build the plugin should ignore.

extensions

  • Type: string[]
  • Default: ['.ts', '.tsx', '.mjs', '.js', '.cjs', '.jsx']

Specifies the files in the build the plugin should operate on. Also, the plugin will search and resolve files for extensions in the order specified for extensionless imports.

include

  • Type: string | RegExp | Array<String | RegExp>
  • Default: /\.[mc]?[jt]sx?$/

A picomatch pattern, or array of patterns, which specifies the files in the build the plugin should operate on.

tsconfig

  • Type: string | false | undefined
  • Default: 'tsconfig.json'

rollup-plugin-swc will read your tsconfig.json or jsconfig.json for default values if your doesn't provide corresponding swc options:

  • The configuration your passed to rollup-plugin-swc will always have the highest priority (higher than tsconfig.json/jsconfig.json).
  • rollup-plugin-swc uses get-tsconfig to find the tsconfig.json/jsconfig.json for the file currently being transpiled.
    • You can also provide a custom filename (E.g. tsconfig.rollup.json, jsconfig.compile.json) to tsconfig option, and rollup-plugin-swc will find and resolve the nearest file with that filename.
    • You can also provide an absolute path (E.g. /path/to/your/tsconfig.json) to tsconfig option, and rollup-plugin-swc will only use the provided path as a single source of truth.
  • You can prevent rollup-plugin-swc from reading tsconfig.json/jsconfig.json by setting tsconfig option to false.
  • jsconfig.json will be ignored if tsconfig.json and jsconfig.json both exist.
  • The extends of tsconfig.json/jsconfig.json is not supported now supported.
  • compilerOptions.target will be passed to swc's jsc.target.
  • compilerOptions.jsxImportSource, compilerOptions.jsxFactory, and compilerOptions.jsxFragmentFactory will be passed to swc's jsc.transform.react.importSource, jsc.transform.react.pragma and jsc.transform.react.pragmaFrag.
  • When compilerOptions.jsx is either react-jsx or react-jsxdev, swc's jsc.transform.react.runtime will be automatic, otherwise it will be classic.
    • compilerOptions.jsx: react-jsxdev will also set swc's jsc.transform.react.development to true.
    • compilerOptions.jsx: preserve will be ignored. swc will always transpile your jsx into javascript code.
  • compilerOptions.baseUrl and compilerOptions.paths will be passed to swc's jsc.baseUrl and jsc.paths directly. They won't affect how rollup resolve your imports. If you have encounted any issue during bundling, please use other plugins to resolve your imports' aliases (e.g., add rollup-plugin-typescript-paths or rollup-plugin-tsconfig-paths before @rollup/plugin-node-resolve).
  • compilerOptions.importHelpers will be passed to swc's jsc.externalHelpers. You will have to have @swc/helpers avaliable in your project when enabled.
  • compilerOptions.experimentalDecorators and compilerOptions.emitDecoratorMetadata will be passed to swc's jsc.parser.decorators and jsc.transform.decoratorMetadata.
  • compilerOptions.esModuleInterop will always be ignored, as swc requires module.type to exist when module.noInterop is given.

Standalone Minify Plugin

If you only want to use swc to minify your bundle:

import { minify } from 'rollup-plugin-swc3'

export default {
  plugins: [
    minify({
      // swc's minify option here
      // mangle: {}
      // compress: {}
    }),
  ],
}

If you want autocompletion in your IDE or type check:

import { minify, defineRollupSwcMinifyOption } from 'rollup-plugin-swc3'

export default {
  plugins: [
    minify(
      defineRollupSwcMinifyOption({
        // swc's minify option here
        // mangle: {}
        // compress: {}
      })
    ),
  ],
}

// or
/** @type {import('@swc/core').JsMinifyOptions} */
const swcMinifyConfig = {}

React Server Component directives ('use client' and 'use server')

Since version 0.9.0, the support for 'use client' and 'use server' has been added:

The support for 'use client' and 'use server' has been separated into a standalone rollup plugin rollup-preserve-directives, maintained by @huozhi and me. The previous preserveUseDirective named export is retained for the backward compatibility.

# npm
npm install -D rollup-preserve-directives
# yarn
yarn add -D rollup-preserve-directives
# pnpm
pnpm add -D rollup-preserve-directives
// rollup.config.js
import { swc } from 'rollup-plugin-swc3';
import preserveDirectives from 'rollup-preserve-directives';

export default {
  input: 'xxxx',
  output: {},
  plugins: [
    swc(),
    // And add `preserveDirectives` plugin after the `swc` plugin
    preserveDirectives()
  ];
}

And that is it!

preserveDirectives supports:

  • Merging duplicated directives in the output bundles

    // src/foo.js
    'use sukka';
    'use foxtail';
    
    export const foo = 'foo';
    
    // src/bar.js
    'use sukka';
    export const bar = 'bar';
    
    // src/index.js
    export { foo } from './foo';
    export { bar } from './bar';
    
    // rollup.config.js
    export default {
      input: 'src/index.js',
      output: { file: 'dist/index.js' }
      plugins: [swc(), preserveDirectives()]
    }
    
    // dist/index.js
    'use sukka';
    'use foxtail';
    
    const foo = 'foo';
    const bar = 'bar';
    
    export { foo, bar };
  • When bundle React Client Component and React Server Component separately, mutiple entries will have their own separated and correct directives:

    // src/client.js
    'use client';
    import { useState } from 'react';
    export const Foo = () => { useState('client-only code') };
    
    // src/server.js
    'use server';
    import 'fs';
    export const bar = 'server only code';
    
    // rollup.config.js
    export default {
      // let rollup bundle client and server separately by adding two entries
      input: {
        client: 'src/client.js',
        server: 'src/server.js'
      },
      // output both client bundle and server bundle in the "dist/" directory
      output: { dir: 'dist/', entryFileName: '[name].js' }
      plugins: [swc(), preserveDirectives()]
    }
    
    // dist/client.js
    'use client';
    import { useState } from 'react';
    const Foo = () => { useState('client-only code') };
    export { Foo };
    
    // dist/server.js
    'use server';
    import 'fs';
    const bar = 'server only code';
    export { bar };

Write your Rollup config in TypeScript

You can write your Rollup config file in rollup.config.ts, and use the following command:

rollup --config rollup.config.ts --configPlugin swc3

TypeScript Declaration File

There are serveral ways to generate declaration file:

  • Use tsc with emitDeclarationOnly, the slowest way but you get type checking, it doesn't bundle the .d.ts files.
  • Use rollup-plugin-dts which generates and bundle .d.ts, also does type checking. It is used by this plugin as well.

Use with Non-react JSX

You can either configure it in your tsconfig.json or in your rollup.config.js.

// Vue JSX
import { swc, defineRollupSwcOption } from 'rollup-plugin-swc3';

export default {
  input: 'xxxx',
  output: {},
  plugins: [
    swc(defineRollupSwcOption({
      jsc: {
        experimental: {
          plugins: [['swc-plugin-vue-jsx', {}]] // npm i swc-plugin-vue-jsx
        }
      }
    })),
  ];
}
// Preact
import { swc, defineRollupSwcOption } from 'rollup-plugin-swc3';

export default {
  input: 'xxxx',
  output: {},
  plugins: [
    swc(defineRollupSwcOption({
      jsc: {
        transform:{
          react: {
          pragma: 'h',
          pragmaFrag: 'Fragment'
          // To use preact/jsx-runtime:
          // importSource: 'preact',
          // runtime: 'automatic'
          }
        }
      }
    })),
  ];
}

rollup-plugin-swc ยฉ Sukka, Released under the MIT License.
Inspired by egoist's rollup-plugin-esbuild.
Authored and maintained by Sukka with help from contributors (list).

Personal Website ยท Blog ยท GitHub @SukkaW ยท Telegram Channel @SukkaChannel ยท Mastodon @[email protected] ยท Twitter @isukkaw ยท Keybase @sukka

Footnotes

  1. If minify is called in Rollup's transform phase, every individual module processed will result in a minify call. However, if minify is called in Rollup's renderChunk phase, the minify will only be called once in one whole pass before Rollup generates bundle, results in a faster build. โ†ฉ

  2. Autocompletion and type checking in your IDE โ†ฉ

  3. mentaljam/rollup-plugin-swc has both main and module fields in package.json, but has๐Ÿ›‘exports field. โ†ฉ

More Repositories

1

Koolshare-Clash

๐Ÿฑ Run Clash Tunnel on Koolshare OpenWrt
ASP
1,279
star
2

nolyfill

Speed up your package installation process, reduce your disk usage, and extend the lifespan of your precious SSD.
TypeScript
1,097
star
3

DisqusJS

๐Ÿ’ฌ Render Disqus comments in Mainland China using Disqus API
TypeScript
591
star
4

Surge

็”ฑ Sukka ๆœ้›†ใ€ๆ•ด็†ใ€็ปดๆŠค็š„ใ€ไธชไบบ่‡ช็”จ็š„ใ€ไป…้€‚็”จไบŽ Surge ็š„ Rule Snippet
JavaScript
583
star
5

hexo-theme-suka

๐ŸŽจModern, powerful and simple theme for Hexo.
CSS
580
star
6

nali-cli

โš“ Parse geoinfo of IP Address without leaving your terminal
JavaScript
393
star
7

zsh-proxy

๐Ÿ”ฉ An oh-my-zsh plugin to configure proxy
Shell
369
star
8

foxact

React Hooks/Utils done right. For Browser, SSR, and React Server Components.
TypeScript
302
star
9

OpenCore-Document-zh_Hans

[้žๅฎ˜ๆ–น/Unofficial] OpenCore Bootloader ๅ‚่€ƒๆ‰‹ๅ†Œ็ฎ€ไฝ“ไธญๆ–‡็ฟป่ฏ‘
JavaScript
238
star
10

cloudflare-workers-async-google-analytics

โ˜๏ธ The Cloudflare Workers implementation of an async Google Analytics
JavaScript
205
star
11

ClashEditor

๐Ÿ“ An editor for writing Clash config
HTML
192
star
12

cloudflare-block-bad-bot-ruleset

๐Ÿšฆ Block malicious crawlers with Cloudflare Firewall Rules
175
star
13

hexo-theme-doku

๐Ÿ“œ Doku, a Hexo theme designed for writing documents.
HTML
145
star
14

zsh-osx-autoproxy

An oh-my-zsh plugin that configures proxy environment variables based on macOS's system preferences automatically
Shell
87
star
15

dotfiles

๐Ÿ”ง My development environment and config
Shell
82
star
16

Lenovo-Y9000X-Hackintosh

Lenovo LEGION Y9000X 2020 (Lenovo LEGION S740-15IRH) Hackintosh
ASL
71
star
17

ThinkPad-E480-Hackintosh

macOS Catalina & Big Sur on ThinkPad E480 (Hackintosh)
ASL
62
star
18

dashflare

An unofficial Cloudflare dashboard built on top of Cloudflare API.
TypeScript
55
star
19

bring-github-old-feed-back

Throw away the GitHub's useless "For You" feed and replace with the old good "Following" feed
TypeScript
53
star
20

forgetti-loader

A webpack/rspack loader and a Next.js plugin that brings an auto-memoization compiler to solves your hook spaghetti. Powered by forgetti which is inspired by React Forget.
TypeScript
52
star
21

CheckSSL

๐Ÿ”’Check your site's SSL status using curl & bash
Shell
41
star
22

vercel-dns-console

An unofficial implementation of Vercel DNS Dashboard
TypeScript
37
star
23

Friends

โ™ฅ๏ธ Friends of @SukkaW
JavaScript
33
star
24

react-compiler-webpack

The webpack/rspack loader for React Compiler
TypeScript
22
star
25

style9-webpack

The another Webpack Plugin for Atomic CSS-in-JS implementation style9
TypeScript
19
star
26

eslint-config-sukka

ESLint configuration of Sukka
TypeScript
17
star
27

stylex-webpack

The another webpack/Next.js Plugin for Facebook StyleX
TypeScript
17
star
28

markdown.css

๐Ÿ“ The simple CSS to replicate the GitHub Markdown style (Sukka Ver.)
CSS
14
star
29

disqusjs-proxy-example

Using Now as Disqus API Proxy
13
star
30

theme-doku-docs

๐Ÿ“œ The documents & demo of hexo-theme-doku
13
star
31

CheckLatency

๐ŸŒ (WIP) A tool that check your latency to cloud provider every regions
JavaScript
13
star
32

memdisk

A library and a CLI to create RAM disk on macOS and Linux.
TypeScript
13
star
33

recipage

๐Ÿ“ƒ Reci(pe)page: Turn a markdown file into one simple page
JavaScript
12
star
34

pure-svg-countdown

HTML
12
star
35

xbits

Convert bytes to a human readable string
TypeScript
12
star
36

SukkaW

My GitHub Profile
11
star
37

Cloudflare-WAF-to-AbuseIPDB

JavaScript
10
star
38

hexo-lute

A markdown renderer for Hexo based on Lute
JavaScript
8
star
39

consolas-powerline

Consolas Nerd Font (Consolas 7.0)
Python
8
star
40

busuanzi

The mirror of busuanzi js
8
star
41

hv-monsterdb-userscript

M-M-M-MONSTER DATABASE!
TypeScript
7
star
42

fast-cidr-tools

cidr-tools but up to 20x faster
TypeScript
7
star
43

eslint-config-sukka-archive

JavaScript
7
star
44

openconnect-snell

Allow Surge to connect to OpenConnect using Docker + Snell Server V4
Shell
6
star
45

suka.css

โœจThe most useless css framework.
CSS
6
star
46

telegram-reply-image-to-messsage-bot

TypeScript
6
star
47

kv4cf

A Modified version of cloudflare/kv-asset-handler, with Non-ASCII URL supported.
JavaScript
6
star
48

hentaiverse-monster-database

M-M-M-MONSTER DATABASE SERVER!
TypeScript
5
star
49

hentaiverse-util-api-userscript

A userscript provided API for other HentaiVerse userscripts
TypeScript
5
star
50

monsterbation-linter

TypeScript
5
star
51

bundled-open-cli

Open stuff like URLs, files, executables, with installation size reduced by 78%. Cross-platform.
TypeScript
5
star
52

bili-mcdn

HTML
4
star
53

Koolshare-OpenWrt-API-Documents

The API documents (unofficial) for Koolshare OpenWrt httpdb
4
star
54

tor-exit-page

An alternative "This is a Tor Exit Router" page
HTML
4
star
55

rcpy

Lightweight, fast, simple and flexible file copy utility for Node.js
TypeScript
4
star
56

teacup.js

๐Ÿต Cache javascript & css files in localStorage
JavaScript
3
star
57

zsh-gitcd

๐Ÿ”ฉ An oh-my-zsh plugin for git clone && cd
Shell
3
star
58

nodelistparser

Surge / Mihomo (Clash.Meta) nodelist / proxy provider parser and generator
TypeScript
2
star
59

sponsors

TypeScript
2
star
60

Hackintosh-Kext-Builder

Shell
1
star
61

BadgeKit

๐Ÿšฉ Get every badge you need for your README
JavaScript
1
star
62

hexo-renderer-pejs

EJS(based on PEJS) renderer for Hexo
JavaScript
1
star
63

untyped-javascript-serialization-benchmark

TypeScript
1
star
64

cidr-tools-wasm

TypeScript
1
star