UNPKG

55.9 kBMarkdownView Raw
1<!-- SHADOW_SECTION_LOGO_START -->
2
3<div><img alt="Logo" src="https://raw.githubusercontent.com/wessberg/rollup-plugin-ts/master/documentation/asset/rollup-plugin-ts-logo.png" height="150" /></div>
4
5<!-- SHADOW_SECTION_LOGO_END -->
6
7<!-- SHADOW_SECTION_DESCRIPTION_SHORT_START -->
8
9> A TypeScript Rollup plugin that bundles declarations, respects Browserslists, and enables seamless integration with transpilers such as babel and swc
10
11<!-- SHADOW_SECTION_DESCRIPTION_SHORT_END -->
12
13<!-- SHADOW_SECTION_BADGES_START -->
14
15<a href="https://npmcharts.com/compare/rollup-plugin-ts?minimal=true"><img alt="Downloads per month" src="https://img.shields.io/npm/dm/rollup-plugin-ts.svg" /></a>
16<a href="https://www.npmjs.com/package/rollup-plugin-ts"><img alt="NPM version" src="https://badge.fury.io/js/rollup-plugin-ts.svg" /></a>
17<a href="https://david-dm.org/wessberg/rollup-plugin-ts"><img alt="Dependencies" src="https://img.shields.io/david/wessberg%2Frollup-plugin-ts.svg" /></a>
18<a href="https://github.com/wessberg/rollup-plugin-ts/graphs/contributors"><img alt="Contributors" src="https://img.shields.io/github/contributors/wessberg%2Frollup-plugin-ts.svg" /></a>
19<a href="https://github.com/prettier/prettier"><img alt="code style: prettier" src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg" /></a>
20<a href="https://opensource.org/licenses/MIT"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg" /></a>
21<a href="https://www.patreon.com/bePatron?u=11315442"><img alt="Support on Patreon" src="https://img.shields.io/badge/patreon-donate-green.svg" /></a>
22
23<!-- SHADOW_SECTION_BADGES_END -->
24
25<!-- SHADOW_SECTION_DESCRIPTION_LONG_START -->
26
27## Description
28
29<!-- SHADOW_SECTION_DESCRIPTION_LONG_END -->
30
31This is first and foremost a TypeScript plugin for Rollup that brings the best of both together in a package that also respects [Browserslists](https://github.com/browserslist/browserslist), bundles declaration files, and enables seamless integration with other transpilers such as [Babel](https://babeljs.io) and [swc](https://swc.rs/).
32
33One of the most powerful features of `rollup-plugin-ts` is declaration bundling and tree-shaking that works seamlessly with code splitting. That means you'll always get the smallest possible declaration files that match exactly what you're exporting, without any superflous type information.
34
35Tooling in the JavaScript ecosystem can often be complex, and this is very much the case when intending to combine TypeScript with other tools such as Babel and Browserslists while still maintaining the [unique emit capabilities of `tsc`](https://github.com/rollup/rollup-plugin-typescript/issues/28). `rollup-plugin-ts` differs from other TypeScript plugins in being opiniated about how some of these tools integrate in order to achieve the most optimal behavior with the smallest possible computational overhead. For example, when combined with another transpiler such as Babel, TypeScript handles diagnostics, declarations, and stripping away types, while Babel is used for syntax transformations.
36
37At the same time, `rollup-plugin-ts` has a very robust test suite that runs tests across all minor versions of TypeScript since v3.4 to ensure that everything works no matter which version of TypeScript you or your team is using.
38
39<!-- SHADOW_SECTION_FEATURES_START -->
40
41### Features
42
43<!-- SHADOW_SECTION_FEATURES_END -->
44
45- Enables you to bundle your TypeScript applications and libraries with Rollup
46- Generates, bundles, and tree-shakes declaration files (`.d.ts`) and fully supports code splitting.
47- Integrates seamlessly with other transpilers such as [Babel](https://babeljs.io) and [swc](https://swc.rs/), such that TypeScript handles diagnostics, declarations, and stripping away types, and another transpiler is used for syntax transformation.
48- Emits Compiler diagnostics and brings them into the Rollup build lifecycle
49- Correctly handles [Emit-less types](https://github.com/rollup/rollup-plugin-typescript/issues/28)
50- Supports Incremental compilation.
51- A [Browserslist](https://github.com/browserslist/browserslist) can be provided instead of a target version of ECMAScript such that your code is transpiled in relation to the baseline of browsers defined in your Browserslist instead.
52- Robust, with a comprehensive test suite that runs against all minor versions of TypeScript from v3.4 and up.
53
54<!-- SHADOW_SECTION_FEATURE_IMAGE_START -->
55
56<!-- SHADOW_SECTION_FEATURE_IMAGE_END -->
57
58<!-- SHADOW_SECTION_BACKERS_START -->
59
60## Backers
61
62[Become a sponsor/backer](https://github.com/wessberg/rollup-plugin-ts?sponsor=1) and get your logo listed here.
63
64| <a href="https://usebubbles.com"><img alt="Bubbles" src="https://uploads-ssl.webflow.com/5d682047c28b217055606673/5e5360be16879c1d0dca6514_icon-thin-128x128%402x.png" height="70" /></a> | <a href="https://github.com/cblanc"><img alt="Christopher Blanchard" src="https://avatars0.githubusercontent.com/u/2160685?s=400&v=4" height="70" /></a> | <a href="https://github.com/ideal-postcodes"><img alt="Ideal Postcodes" src="https://avatars.githubusercontent.com/u/4996310?s=200&v=4" height="70" /></a> | <a href="https://www.xerox.com"><img alt="Xerox" src="https://avatars.githubusercontent.com/u/9158512?s=200&v=4" height="70" /></a> | <a href="https://changelog.me"><img alt="Trent Raymond" src="https://avatars.githubusercontent.com/u/1509616?v=4" height="70" /></a> |
65| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
66| [Bubbles](https://usebubbles.com)<br><strong>Twitter</strong>: [@usebubbles](https://twitter.com/usebubbles) | [Christopher Blanchard](https://github.com/cblanc) | [Ideal Postcodes](https://github.com/ideal-postcodes) | [Xerox](https://www.xerox.com) | [Trent Raymond](https://changelog.me) |
67
68### Patreon
69
70<a href="https://www.patreon.com/bePatron?u=11315442"><img alt="Patrons on Patreon" src="https://img.shields.io/endpoint.svg?url=https%3A%2F%2Fshieldsio-patreon.vercel.app%2Fapi%3Fusername%3Dwessberg%26type%3Dpatrons" width="200" /></a>
71
72<!-- SHADOW_SECTION_BACKERS_END -->
73
74<!-- SHADOW_SECTION_TOC_START -->
75
76## Table of Contents
77
78- [Description](#description)
79 - [Features](#features)
80- [Backers](#backers)
81 - [Patreon](#patreon)
82- [Table of Contents](#table-of-contents)
83- [Install](#install)
84 - [npm](#npm)
85 - [Yarn](#yarn)
86 - [pnpm](#pnpm)
87 - [Peer Dependencies](#peer-dependencies)
88- [Usage](#usage)
89 - [Using it with just Typescript](#using-it-with-just-typescript)
90 - [Typescript and tslib helpers](#typescript-and-tslib-helpers)
91 - [Combining Typescript with a Browserslist](#combining-typescript-with-a-browserslist)
92 - [Using the plugin with Typescript, but without Browserslists](#using-the-plugin-with-typescript-but-without-browserslists)
93 - [Combining Typescript with Babel](#combining-typescript-with-babel)
94 - [`@babel/preset-env` behavior (and how to opt out)](#babelpreset-env-behavior-and-how-to-opt-out)
95 - [Special handling for minification plugins/presets](#special-handling-for-minification-pluginspresets)
96 - [`@babel/runtime` and external helpers](#babelruntime-and-external-helpers)
97 - [`@babel/runtime` and polyfills](#babelruntime-and-polyfills)
98 - [Combining Typescript with swc](#combining-typescript-with-swc)
99 - [Using `Custom Transformers`](#using-custom-transformers)
100- [Declaration files](#declaration-files)
101- [Examples](#examples)
102 - [Pure Typescript example](#pure-typescript-example)
103 - [Typescript with Browserslist example](#typescript-with-browserslist-example)
104 - [Typescript, Babel, and Browserslist example](#typescript-babel-and-browserslist-example)
105 - [Typescript, swc, and Browserslist example](#typescript-swc-and-browserslist-example)
106 - [Pure Typescript with Custom Transformers](#pure-typescript-with-custom-transformers)
107 - [Advanced example of using Typescript, Babel, and Browserslists together](#advanced-example-of-using-typescript-babel-and-browserslists-together)
108 - [Passing a specific TypeScript version](#passing-a-specific-typescript-version)
109- [Hooks](#hooks)
110 - [The `outputPath` hook](#the-outputpath-hook)
111 - [The `diagnostics` hook](#the-diagnostics-hook)
112 - [The `declarationStats` hook](#the-declarationstats-hook)
113 - [The `externalTypes` property for `DeclarationChunkStats`](#the-externaltypes-property-for-declarationchunkstats)
114- [Full list of plugin options](#full-list-of-plugin-options)
115 - [`transpiler`](#transpiler)
116 - [`babelConfig`](#babelconfig)
117 - [`swcConfig`](#swcconfig)
118 - [`tsconfig`](#tsconfig)
119 - [`browserslist`](#browserslist)
120 - [`cwd`](#cwd)
121 - [`typescript`](#typescript)
122 - [`transformers`](#transformers)
123 - [`include`](#include)
124 - [`exclude`](#exclude)
125 - [`transpileOnly`](#transpileonly)
126 - [`fileSystem`](#filesystem)
127 - [`hook`](#hook)
128- [Ignored/overridden options](#ignoredoverridden-options)
129 - [Ignored/overridden TypeScript options](#ignoredoverridden-typescript-options)
130 - [Behavior of esModuleInterop](#behavior-of-esmoduleinterop)
131 - [Ignored/overridden Babel options](#ignoredoverridden-babel-options)
132 - [Ignored/overridden swc options](#ignoredoverridden-swc-options)
133 - [Default Babel plugins](#default-babel-plugins)
134- [Contributing](#contributing)
135- [Maintainers](#maintainers)
136- [FAQ](#faq)
137 - [Does this plugin work with Code Splitting?](#does-this-plugin-work-with-code-splitting)
138 - [Why wouldn't you use just TypeScript?](#why-wouldnt-you-use-just-typescript)
139 - [Okay, then why wouldn't you use just babel?](#okay-then-why-wouldnt-you-use-just-babel)
140 - [When combined with Babel, what does TypeScript do, and what does Babel do?](#when-combined-with-babel-what-does-typescript-do-and-what-does-babel-do)
141 - [When combined with swc, what does TypeScript do, and what does Babel do?](#when-combined-with-swc-what-does-typescript-do-and-what-does-babel-do)
142 - [Why is @babel/plugin-transform-runtime and tslib included by default?](#why-is-babelplugin-transform-runtime-and-tslib-included-by-default)
143- [Starter templates](#starter-templates)
144- [License](#license)
145
146<!-- SHADOW_SECTION_TOC_END -->
147
148<!-- SHADOW_SECTION_INSTALL_START -->
149
150## Install
151
152### npm
153
154```
155$ npm install rollup-plugin-ts --save-dev
156```
157
158### Yarn
159
160```
161$ yarn add rollup-plugin-ts --dev
162```
163
164### pnpm
165
166```
167$ pnpm add rollup-plugin-ts --save-dev
168```
169
170### Peer Dependencies
171
172`rollup-plugin-ts` depends on `rollup` and `typescript`, so you need to manually install these as development dependencies as well.
173
174You may also need to install additional peer dependencies such as `@babel/core`, `@babel/runtime`, `@babel/preset-env`, `@babel/plugin-transform-runtime`, `@swc/core`, or `@swc/helpers` depending on the features you are going to use. Refer to the documentation for the specific cases where any of these may be relevant.
175
176<!-- SHADOW_SECTION_INSTALL_END -->
177
178<!-- SHADOW_SECTION_USAGE_START -->
179
180## Usage
181
182<!-- SHADOW_SECTION_USAGE_END -->
183
184Using the plugin is as simple as it can be. Here's an example within a Rollup config:
185
186```javascript
187import ts from "rollup-plugin-ts";
188export default {
189 // ...
190 plugins: [
191 ts({
192 /* Plugin options */
193 })
194 ]
195};
196```
197
198Without any options, the plugin will _"just work"_:
199
200- The `tsconfig.json` file closest to the current working directory will be resolved, if any. Otherwise, the default Typescript options will be used.
201- The `.browserslistrc` file or `browserslist` property within the `package.json` file closest to the current working directory will be resolved and used to decide the Typescript ECMAScript version target, if any. Otherwise, the declared `target` within the resolved `tsconfig.json` file will be used, if any such file exists, and if not, the default Typescript target will be used.
202
203### Using it with just Typescript
204
205This plugin works very well with just Typescript.
206The `tsconfig.json` file closest to your project will be resolved and used in combination with Rollup.
207If your config has a different name, or if you use different configs dynamically depending on the environment, you can provide the location for the `tsconfig` in the plugin options:
208
209```javascript
210ts({
211 tsconfig: PRODUCTION ? "tsconfig.prod.json" : "tsconfig.json"
212});
213```
214
215You an also pass in [CompilerOptions](https://www.typescriptlang.org/docs/handbook/compiler-options.html) directly, rather than provide the path to a `tsconfig`:
216
217```javascript
218ts({
219 tsconfig: {
220 target: ScriptTarget.ES2018,
221 allowSyntheticDefaultImports: true,
222 allowJs: true
223 }
224});
225```
226
227You can also pass in a function that receives whatever `CompilerOptions` that could be resolved relative to the current working directory, but then allow you to override the options:
228
229```javascript
230ts({
231 tsconfig: resolvedConfig => ({...resolvedConfig, allowJs: false})
232});
233```
234
235The above example is based on the assumption that a file can be resolved with the name `tsconfig.json`, and if not, the Typescript's default `CompilerOptions` will be used.
236But if you want to provide the name of the `tsconfig` to override, you can also pass in an object following the following form:
237
238```javascript
239ts({
240 tsconfig: {
241 fileName: "my-awesome-tsconfig.json",
242 hook: resolvedConfig => ({...resolvedConfig, allowJs: false})
243 }
244});
245```
246
247If there is a `.browserslistrc` file or the nearest `package.json` contains a Browserslist configuration, a target ECMAScript version will be decided based on that one, rather than respecting the `target` property of the matched `tsconfig`.
248If you do not want this behavior, you can [disable it as described here](#using-the-plugin-with-typescript-but-without-browserslists).
249
250#### Typescript and tslib helpers
251
252This plugin makes sure that the helper functions that may be emitted within the output generated by Typescript will not be duplicated across files and chunks. Instead, they will automatically be divided into chunks and imported across Rollup chunks.
253You don't have to do anything!
254
255### Combining Typescript with a Browserslist
256
257If there is a `.browserslistrc` file or the nearest `package.json` contains a Browserslist configuration, this is the default behavior! Rather than use the `target` property of the nearest `tsconfig`, it will be decided based on the Browserslist.
258
259You can explicitly pass in Browserslist options. Here's an example with a raw Browserslist query:
260
261```javascript
262ts({
263 browserslist: ["last 1 version", "> 1%"]
264});
265```
266
267You can also provide a configuration object instead of a raw query. Here's one with a baked-in query:
268
269```javascript
270ts({
271 browserslist: {
272 query: ["last 1 version", "> 1%"]
273 }
274});
275```
276
277...And here's one with a `path` property pointing to a file that contains a Browserslist:
278
279```javascript
280ts({
281 browserslist: {
282 path: ".mybrowserslistrc"
283 }
284});
285```
286
287#### Using the plugin with Typescript, but without Browserslists
288
289If no Browserslist can be found, or if you simply don't want to use one, that's completely OK!
290In such cases, the `target` property of the nearest `tsconfig` will be used (or use the Typescript default setting if no such file exists).
291
292You can explicitly request that no Browserslist will be used by setting the `browserslist` property to `false` in the plugin options:
293
294```javascript
295ts({
296 browserslist: false
297});
298```
299
300### Combining Typescript with Babel
301
302This plugin makes it really easy to use Typescript for reporting diagnostics, generating declaration files, and stripping types, but then using Babel for all other syntax transformations.
303One very strong use case for this is to use [`@babel/preset-env`](https://babeljs.io/docs/en/babel-preset-env). Another one is that you get the entire ecosystem of Babel plugins at your disposal.
304
305To use Babel, first set the `transpiler` plugin option to `"babel"`:
306
307```javascript
308ts({
309 transpiler: "babel"
310});
311```
312
313Now, all that remains is to simply install the peer dependencies relevant to `babel`. Please install `@babel/core`, `@babel/runtime`, `@babel/plugin-transform-runtime`, and `@babel/preset-env` as well with your package manager:
314
315**npm**
316
317```
318$ npm install @babel/core @babel/runtime @babel/plugin-transform-runtime @babel/preset-env --save-dev
319```
320
321**Yarn**
322
323```
324$ yarn add @babel/core @babel/runtime @babel/plugin-transform-runtime @babel/preset-env --dev
325```
326
327**pnpm**
328
329```
330$ pnpm add @babel/core @babel/runtime @babel/plugin-transform-runtime @babel/preset-env --save-dev
331```
332
333Don't worry if you don't, `rollup-plugin-ts` will warn you about exactly which dependencies are missing once you run it.
334
335Once you're done installing peer dependencies, that's it! The plugin will attempt to locate a `babel.config.js` file or a `.babelrc` file and use the options, plugins, and presets found there.
336By default, some combination of presets and plugins will be applied depending on the config options you provide, while others will be forced at all times for interoperability reasons. See [this section](#default-babel-plugins) for more details.
337
338#### `@babel/preset-env` behavior (and how to opt out)
339
340By default, when using Babel as the transpiler, `@babel/preset-env` will be used as a preset that respects the browserslist that was either provided directly as a plugin option, or was resolved inside the root of your project, or was computed based on your `tsconfig.json` file.
341
342If you don't want this behavior, simply pass the `browserslist: false` option to the plugin. Doing so will never apply `@babel/preset-env` and not apply any additional syntax transformations:
343
344```javascript
345ts({
346 transpiler: "babel",
347 browserslist: false
348});
349```
350
351#### Special handling for minification plugins/presets
352
353This plugin will apply syntax transformations from Babel presets and plugins on a file-by-file basis. However, if a minification-related plugin or preset such as [babel-preset-minify](https://github.com/babel/minify/tree/master/packages/babel-preset-minify) is found within the Babel options,
354these transformations will be applied per chunk. This enables the minification presets and plugins to perform better as it can now mangle in relation to the entire chunk and better remove unwanted characters such as whitespace.
355All of this works automatically.
356
357#### `@babel/runtime` and external helpers
358
359This plugin will automatically make sure to avoid duplication of emitted Babel helpers. Rollup will automatically split these into chunks and re-use them across the chunks that Rollup generates.
360You don't have to do anything.
361
362#### `@babel/runtime` and polyfills
363
364Babel supports injecting polyfills where needed and in relation to the target environment. By default, this plugin **will not** add polyfills to your chunks since there are arguably better ways of applying polyfills such as lazy-loading depending on feature support or using something like [Polyfill.app](https://github.com/wessberg/polyfiller).
365If you would like this behavior, simply add either `@babel/plugin-transform-runtime` to your Babel config with the `corejs` option set to true, or add `@babel/preset-env` to your Babel config with the `useBuiltIns` option set to `usage`.
366
367### Combining Typescript with swc
368
369Just like with [Babel](#combining-typescript-with-babel), this plugin makes it trivial to use TypeScript for reporting diagnostics, generating declaration files, and stripping types, but then using swc for all other syntax transformations.
370
371Swc is a much faster alternative to Babel, built in Rust, that attempts to be as close to a drop-in replacement for Babel as possible. It is not nearly as mature and doesn't have as big a plugin ecosystem yet, but can often be much faster than Babel. And like Babel, it also has [first-class support for Browserslists](https://swc.rs/docs/configuration/supported-browsers) which will be used to decide which syntax transformations to apply depending on language support in the target environments.
372
373To use swc, first set the `transpiler` plugin option to `"swc"`:
374
375```javascript
376ts({
377 transpiler: "swc"
378});
379```
380
381Now, all that remains is to simply install the peer dependencies relevant to `swc`. Please install `@swc/core` and `@swc/helpers` as well with your package manager:
382
383**npm**
384
385```
386$ npm install @swc/core @swc/helpers --save-dev
387```
388
389**Yarn**
390
391```
392$ yarn add @swc/core @swc/helpers --dev
393```
394
395**pnpm**
396
397```
398$ pnpm add @swc/core @swc/helpers --save-dev
399```
400
401Don't worry if you don't, `rollup-plugin-ts` will warn you about exactly which dependencies are missing once you run it.
402
403Once you're done installing peer dependencies, that's it! The plugin will attempt to locate a `.swcrc` file and use the options found there.
404By default, some combination of options will be applied depending on the config options you provide, while others will be forced at all times for interoperability reasons. See [this section](#default-babel-plugins) for more details.
405
406### Using `Custom Transformers`
407
408This plugin enables you to pass in [`Custom Transformers`](https://github.com/Microsoft/TypeScript/pull/13940) which allows you to transform the Typescript AST during code transpilation.
409This enables you to very efficiently transform Typescript before code generation and additionally enables you to use this plugin with tools that leverage this, such as some modern web frameworks and libraries do.
410
411## Declaration files
412
413Typescript declaration files are normally distributed in a folder structure that resembles the structure of the source folder.
414With `tsc`, you would get something like this:
415
416<img alt="TSC emitted code" src="https://raw.githubusercontent.com/wessberg/rollup-plugin-ts/master/documentation/asset/tsc-output-example.png" height="250" />
417
418Rollup is a bundler, and with it, we can produce clean, small files that are easy to distribute.
419With `rollup-plugin-ts`, declaration files will be bundled, tree-shaken and emitted alongside the chunks emitted by Rollup:
420
421<img alt="Plugin emitted code" src="https://raw.githubusercontent.com/wessberg/rollup-plugin-ts/master/documentation/asset/plugin-output-example.png" height="250" />
422
423And, it even works in complex code splitting scenarios:
424
425<img alt="Plugin emitted code with code splitting" src="https://raw.githubusercontent.com/wessberg/rollup-plugin-ts/master/documentation/asset/plugin-output-example-code-splitting.png" height="250" />
426
427## Examples
428
429### Pure Typescript example
430
431```javascript
432ts({
433 // If your tsconfig is already called 'tsconfig.json', this option can be left out
434 tsconfig: "tsconfig.json",
435 // If there is no .browserslistrc within your project, and if your package.json doesn't include a Browserslist property, this option can be left out
436 browserslist: false
437});
438```
439
440### Typescript with Browserslist example
441
442[As described here](#combining-typescript-with-a-browserslist), by default, the plugin will attempt to locate a Browserslist automatically. This example
443shows how you can provide one explicitly
444
445```javascript
446ts({
447 browserslist: ["last 1 version", "> 1%"]
448});
449
450// or
451ts({
452 browserslist: {path: ".mybrowserslistrc"}
453});
454```
455
456### Typescript, Babel, and Browserslist example
457
458[As described here](#combining-typescript-with-babel), a `babel.config.js` or `.babelrc` file will automatically be found by the plugin if available. This example shows how you can provide one explicitly.
459And, [as described here](#typescript-with-browserslist-example), the same goes for Browserslists.
460
461```javascript
462ts({
463 transpiler: "babel",
464 browserslist: ["last 1 version", "> 1%"],
465 babelConfig: {
466 plugins: ["my-babel-plugin"]
467 }
468});
469```
470
471### Typescript, swc, and Browserslist example
472
473[As described here](#combining-typescript-with-swc), a `.swcrc` file will automatically be found by the plugin if available. This example shows how you can provide one explicitly.
474And, [as described here](#typescript-with-browserslist-example), the same goes for Browserslists.
475
476```javascript
477ts({
478 transpiler: "swc",
479 browserslist: ["last 1 version", "> 1%"],
480 swcConfig: {
481 minify: true
482 }
483});
484```
485
486### Pure Typescript with Custom Transformers
487
488```javascript
489ts({
490 transformers: {
491 before: [myTransformer1, myTransformer2],
492 after: [myTransformer3, myTransformer4],
493 afterDeclarations: [myTransformer5, myTransformer6]
494 }
495});
496```
497
498### Advanced example of using Typescript, Babel, and Browserslists together
499
500This example shows how you can use this plugin to accomplish quite advanced things:
501
502```javascript
503const IS_PRODUCTION = process.env.NODE_ENV === "production";
504const BUNDLE_TARGET = process.env.BUNDLE_TARGET;
505const APP_ROOT = "/some/project/root/folder";
506const awesomeFrameworkTransformers = getAwesomeFrameworkCustomTransformers();
507
508ts({
509 // Use Babel for Syntax transformations
510 transpiler: "babel",
511 // Don't use process.cwd(), but instead another root directory
512 cwd: APP_ROOT,
513 // Load a different tsconfig file in production
514 tsconfig: IS_PRODUCTION ? "tsconfig.prod.json" : "tsconfig.json",
515 // Load a different browserslist if currently targeting a modern environment
516 browserslist: {
517 path: BUNDLE_TARGET === "modern" ? ".browserslistrc-modern" : ".browserslistrc-legacy"
518 },
519 // Load a different babel config file in production
520 babelConfig: IS_PRODUCTION ? "babel.config.prod.js" : "babel.config.js",
521
522 // Exclude files within node_modules when not in production
523 exclude: IS_PRODUCTION ? [] : ["node_modules/**/*.*"],
524
525 // Apply CustomTransformers, for example to transform the Source Code with a framework that uses some
526 transformers: awesomeFrameworkTransformers
527});
528```
529
530### Passing a specific TypeScript version
531
532You can use pass a specific TypeScript to use as an option. This may be useful if you are using different TypeScript versions across packages inside a monorepo and you want to use a specific one with `rollup-plugin-ts`:
533
534```typescript
535ts({
536 typescript: specialTypescriptVersion
537});
538```
539
540## Hooks
541
542`rollup-plugin-ts` provides a few hooks that allow you to hook into and augment the internal behavior of the plugin.
543
544These can be provided in the plugin options for the `hook` property:
545
546```typescript
547ts({
548 hook: {
549 // Add hooks here
550 }
551});
552```
553
554The next few subsections describe the different hooks that can be provided
555
556### The `outputPath` hook
557
558Type: `(path: string, kind: "declaration" | "declarationMap" | "buildInfo") => string | undefined`
559
560The `outputPath` hook can be used to rewrite the location on the filesystem that assets produced by `rollup-plugin-ts` are written to.
561It is invoked immediately before assets such as _declarations_ or _declaration maps_ are emitted.
562
563The hook is invoked with the output path as well as the kind of asset the path represents as arguments.
564If you return a `string` from the hook, the alternative location will be used instead. If you return undefined, the current path will be used.
565
566```typescript
567ts({
568 hook: {
569 outputPath: (path, kind) => rewritePathSomehow(path, kind)
570 }
571});
572```
573
574For example, the `path` may be `/some/path/index.d.ts`, and `kind` be `declaration`, and you might want to rewrite this to `/some/path/my-typings.d.ts`.
575
576### The `diagnostics` hook
577
578Type: `(diagnostics: readonly Diagnostic[]) => readonly Diagnostic[]|undefined`
579
580The `diagnostics` hook can be used to read, alter, and extend the diagnostics generated by TypeScript immediately before they are emitted as errors via Rollup.
581Normally, Rollup will crash on the first discovered error, but there may be several diagnostics, all of which may be of interest to you. This hook gives you access to all of them.
582
583You can also use this hook if you want to silence specific kinds of Diagnostics or even add your own.
584
585### The `declarationStats` hook
586
587Type: `(stats: DeclarationStats) => DeclarationStats|undefined`
588
589The `declarationStats` hook can be used to get relevant stats produced while bundling declarations.
590The hook calls the given callback with a stats object as the first argument.
591The stats object has the following type information:
592
593```typescript
594// A Record from chunk file names to their stats
595type DeclarationStats = Record<string, DeclarationChunkStats>;
596
597interface DeclarationChunkStats {
598 // An array of the external type dependencies for a declaration chunk
599 externalTypes: ExternalType[];
600}
601
602interface ExternalType {
603 // The name of the external library that provides the typings. For example, "typescript" or "@types/node"
604 library: string;
605 // The version of the referenced external library
606 version: string;
607}
608```
609
610##### The `externalTypes` property for `DeclarationChunkStats`
611
612The `externalTypes` property of declaration chunk stats objects can be useful, for example, if you want to get a hook into which external type dependencies that remain
613after bundling and tree-shaking and that you should declare as `dependencies` of your library.
614
615Here's an example of how you might use the hook:
616
617```typescript
618ts({
619 hook: {
620 declarationStats: declarationStats => console.log(declarationStats)
621 }
622});
623```
624
625The example above could log something like the following to the console:
626
627```typescript
628{
629 "index.d.ts": {
630 externalTypes: [
631 { library: "typescript", version: "3.9.2" },
632 { library: "@types/node", version: "14.0.26" }
633 ]
634 },
635 "some-other-chunk.d.ts": {
636 externalTypes: [
637 { library: "some-other-external-library", version: "1.2.3" }
638 ]
639 }
640}
641```
642
643This gives you an easy way to track which external type dependencies remain in your bundled and tree-shaken declarations and that should be declared as dependencies of your library.
644
645## Full list of plugin options
646
647The plugin options are documented in more detail across this README, but the full list of options is:
648
649#### `transpiler`
650
651Type: `"typescript" | "babel" | "swc"`
652
653Can be any of `"babel"`, `"swc"`, or `"typescript"` (default: `"typescript"`).
654See [this section](#combining-typescript-with-babel) and [this section](#when-combined-with-babel-what-does-typescript-do-and-what-does-babel-do) for details on how `rollup-plugin-ts` works when `"babel"` is being used as a transpiler, and [this section](#combining-typescript-with-swc) for how it works when `"swc"` is being used as a transpiler.
655
656#### `babelConfig`
657
658Type: `string | Partial<BabelConfig>`
659
660This option will only be respected when `"babel"` is being used as the `transpiler` and can be used to provide a [Babel config](https://babeljs.io/docs/en/options) or a path to one.
661
662#### `swcConfig`
663
664Type: `string | Partial<SwcConfig>`
665
666This option will only be respected when `"swc"` is being used as the `transpiler` and can be used to provide a [swc config](https://swc.rs/docs/configuration/swcrc) or a path to one.
667
668#### `tsconfig`
669
670Type: `string | Partial<CompilerOptions> | Partial<Record<keyof CompilerOptions, string | number | boolean>> | ParsedCommandLine | TsConfigResolver | TsConfigResolverWithFileName`
671
672Provide the TypeScript [CompilerOptions](https://www.typescriptlang.org/docs/handbook/compiler-options.html) to use, or a path to a `tsconfig` with this property.
673See [this section](#using-it-with-just-typescript) for details on the many ways this property can be configured.
674
675#### `browserslist`
676
677Type: `false | string[] | string | BrowserslistConfig`
678
679Provide the [Browserslist](https://github.com/browserslist/browserslist) to use, or a path to a `.browserslistrc` with this property.
680See [this section](#combining-typescript-with-a-browserslist) for details on the many ways this property can be configured.
681
682#### `cwd`
683
684Type: `string`
685
686Use this property to overwrite whatever is considered the root directory. The default value is `process.cwd()`.
687
688#### `typescript`
689
690Type: `typeof import("typescript")`
691
692Use this property to pass a specific version of TypeScript to use.
693
694#### `transformers`
695
696Type: `(CustomTransformers | CustomTransformersFunction)[] | CustomTransformers | CustomTransformersFunction`
697
698Use this property to provide TypeScript [`CustomTransformers`](https://github.com/Microsoft/TypeScript/pull/13940).
699See [this section](#using-customtransformers) for more details on how to configure this property.
700
701#### `include`
702
703Type: `string[]|string`
704
705This option takes a minimatch pattern or an array of minimatch patterns and only transforms files with filenames that the pattern matches.
706
707#### `exclude`
708
709Type: `string[]|string`
710
711This option takes a minimatch pattern or an array of minimatch patterns and only transforms files with filenames that the pattern doesn't match.
712
713#### `transpileOnly`
714
715Type: `boolean`
716
717If this option is `true`, diagnostics won't be generated. This will improve performance since TypeScript but ignores all syntactical and semantic errors or warnings that may arise.
718
719#### `fileSystem`
720
721Optionally the FileSystem to use. This is useful for example when you want to provide a virtual FileSystem to read from or write to.
722Note that this must conform with [the `System` interface declared by TypeScript](https://github.com/microsoft/TypeScript/blob/main/src/compiler/sys.ts#L1159), rather than the `fs` module.
723
724#### `hook`
725
726Use this property to get hooks into the internals of `rollup-plugin-ts`.
727See [this section](#hooks) for more details.
728
729## Ignored/overridden options
730
731TypeScript and Babel are powerful tools in their own right. Combined with Rollup, they become even more powerful.
732To provide a seamless experience, Rollup always take precedence when conflicts arise. As a natural consequence of this, some options provided to TypeScript and Babel will be ignored or overridden.
733
734### Ignored/overridden TypeScript options
735
736The following [CompilerOptions](https://www.typescriptlang.org/docs/handbook/compiler-options.html) from a `tsconfig` will be ignored:
737
738| Property | Reason |
739| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
740| `outDir` | Rollup, not TypeScript, will decide where to emit chunks. |
741| `module` | Rollup, not TypeScript, is the decider of which module system(s) to target based on your Rollup configuration. |
742| `outFile` | This option produces flat output and only works with the module formats AMD and SystemJS. Rollup will be the decider of how to split code. |
743| `sourceMap` | TypeScript will always be instructed to produce SourceMaps. Rollup then decides whether or not to include them (and if they should be inlined). |
744| `inlineSourceMap` | TypeScript will always be instructed to produce SourceMaps. Rollup then decides whether or not to include them (and if they should be inlined). |
745| `inlineSources` | Since `inlineSourceMap` is ignored, this option won't take effect. |
746| `importHelpers` | Helpers will always be imported. This makes it possible for Rollup to code-split properly and share TypeScript helpers across chunks. |
747| `moduleResolution` | Node-module resolution will always be used. This is required for `importHelpers` to work and in general, to make TypeScript able to resolve external libraries. Note that you still need to add the [nodeResolve](https://github.com/rollup/rollup-plugin-node-resolve) plugin in order to include external libraries within your bundle unless `allowJs` is `true` within your `tsconfig` |
748| `noEmit` | TypeScript should always be able to emit assets, but those will be delegated to Rollup. |
749| `noEmitOnError` | See above. |
750| `emitDeclarationOnly` | See above. |
751| `noEmitHelpers` | TypeScript should always be able to emit helpers, since the `importHelpers` option is forced |
752| `noResolve` | TypeScript should always be able to resolve things. Otherwise, compilation might break. |
753| `watch` | Rollup, not TypeScript, will watch files if run in watch mode. Efficient caching will still be used for optimum performance. |
754| `preserveWatchOutput` | See above |
755
756The following additional options will also be ignored:
757
758| Property | Reason |
759| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
760| `include` | Rollup itself will decide which files to include in the transformation process based on your code. This plugin itself takes a `include` property which you should use instead if you want to explicitly allow specific files or globs. |
761| `exclude` | See above. |
762
763#### Behavior of esModuleInterop
764
765Given that Rollup, not TypeScript, is the decider of which module system(s) to target based on your Rollup configuration, TypeScript will always emit ES modules that Rollup can understand and work with.
766
767The `esModuleInterop` option to TypeScript is respected, but its emit-characteristics won't have an impact on your bundle. Instead, you may consult [the Rollup documentation for the `interop` option](https://rollupjs.org/guide/en/#outputinterop) to achieve
768the same thing with Rollup.
769
770### Ignored/overridden Babel options
771
772The following [Babel options](https://babeljs.io/docs/en/options) will be ignored:
773
774| Property | Reason |
775| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
776| `sourceMaps` | Babel will always be instructed to produce SourceMaps. Rollup then decides whether or not to include them (and if they should be inlined). |
777| `cwd` | The `cwd` option provided to the plugin will always be used. |
778| `include` | Rollup itself will decide which files to include in the transformation process based on your code. This plugin itself takes a `include` property which you should use instead if you want to explicitly allow specific files or globs. |
779| `exclude` | See above |
780| `ignore` | See above |
781| `only` | See above |
782| `sourceType` | Will always use `module`. Rollup will then decide what to do based on the output format |
783
784### Ignored/overridden swc options
785
786The following [Babel options](https://swc.rs/docs/configuration/swcrc) will be ignored:
787
788| Property | Reason |
789| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
790| `sourceMaps` | swc will always be instructed to produce SourceMaps. Rollup then decides whether or not to include them (and if they should be inlined). |
791| `cwd` | The `cwd` option provided to the plugin will always be used. |
792| `cwd` | See above. |
793| `test` | Rollup itself will decide which files to include in the transformation process based on your code. This plugin itself takes a `include` property which you should use instead if you want to explicitly allow specific files or globs. |
794| `exclude` | See above |
795| `isModule` | Will always use `true`. Rollup will then decide what to do based on the output format |
796
797### Default Babel plugins
798
799If you decide to use Babel as the transpiler with the `transpiler` plugin option set to `"babel"`, some best-practice default plugins and presets will be applied such that you don't have to configure anything on your own.
800By default, the plugin will conditionally apply the `@babel/preset-env` preset if a Browserslist is provided or located, as well as plugins for handling [shipped proposals](https://babeljs.io/docs/en/babel-preset-env#shippedproposals). And, the `@babel/plugin-runtime` plugin will be used for extracting Babel helpers and reusing them across your chunks to avoid code duplication.
801
802If you provide these presets or plugins yourself through the found or provided Babel config, _your_ config options will take precedence.
803
804Here's table with a full overview of the specifics:
805
806| Preset/Plugin | Condition | Reason |
807| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
808| `@babel/preset-env` | A Browserslist is provided or found automatically, and you don't provide this preset yourself within your Babel config | This preset enables you to base your syntax transformations on the specific browsers/environment you want your application or library to target. It will "_Just Work"_ |
809| `@babel/plugin-transform-runtime` | You don't provide this plugin yourself within your Babel config | Depending on your configuration, async functions may be rewritten to use [Regenerator Runtime](https://github.com/facebook/regenerator/tree/master/packages/regenerator-runtime), and there may be one or more Babel helpers injected within your code. `@babel/plugin-runtime` allows this plugin to avoid duplicating these helpers, and instead make them shared across Chunks seamlessly via Rollup. |
810
811<!-- SHADOW_SECTION_CONTRIBUTING_START -->
812
813## Contributing
814
815Do you want to contribute? Awesome! Please follow [these recommendations](./CONTRIBUTING.md).
816
817<!-- SHADOW_SECTION_CONTRIBUTING_END -->
818
819<!-- SHADOW_SECTION_MAINTAINERS_START -->
820
821## Maintainers
822
823| <a href="mailto:frederikwessberg@hotmail.com"><img alt="Frederik Wessberg" src="https://avatars2.githubusercontent.com/u/20454213?s=460&v=4" height="70" /></a> |
824| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
825| [Frederik Wessberg](mailto:frederikwessberg@hotmail.com)<br><strong>Twitter</strong>: [@FredWessberg](https://twitter.com/FredWessberg)<br><strong>Github</strong>: [@wessberg](https://github.com/wessberg)<br>_Lead Developer_ |
826
827<!-- SHADOW_SECTION_MAINTAINERS_END -->
828
829<!-- SHADOW_SECTION_FAQ_START -->
830
831## FAQ
832
833<!-- SHADOW_SECTION_FAQ_END -->
834
835#### Does this plugin work with Code Splitting?
836
837Absolutely, even with Declaration files. Things will work seamlessly.
838
839#### Why wouldn't you use just TypeScript?
840
841The TypeScript compiler, while extremely powerful, has the restriction that it can only target a specific ECMAScript version.
842In reality, browsers and other ECMAScript environments has varying support for newer language features.
843Some browsers support even those features that haven't been publicized yet, while others support only parts of the latest language features.
844
845In effect, a browser may support a lot of modern features such as classes and proper lexical scoping, but lack others.
846With TypeScript, it's _"all-or-nothing"_: If you want to support a Browser with partial support, you must target the latest publicized ECMAScript version that the browser fully supports.
847
848Babel, on the other hand, is far more granular in its design and applies syntax transformations on a feature-by-feature basis.
849Combined with something like `@babel/preset-env`, individual transformations can be applied for only those language features that are missing.
850This means that you can use things like classes and lexical scoping in browsers that otherwise doesn't fully support all of the ES2015 specification.
851
852#### Okay, then why wouldn't you use just babel?
853
854Babel has recently received support for [parsing and transforming TypeScript](https://babeljs.io/docs/en/babel-plugin-transform-typescript). It would be intriguing to just use Babel for everything. However, there are significant caveats:
855
856The Babel compiler works on a file-by-file basis, meaning it is simple to use and reason about, whereas the TypeScript compiler works with _Programs_, or in other words sets of related _SourceFiles_.
857This gives TypeScript the advantage over Babel that it has a greater understanding of your codebase in general and can understand your types across files.
858In the context of this plugin, this enables TypeScript to do things that you simply wouldn't be able to do with the TypeScript plugin for Babel:
859
8601. Emit TypeScript diagnostics
8612. Emit TypeScript declaration (`.d.ts`) files and TypeScript declaration map (`.d.ts.map`) files.
8623. Remove type-only imports that wouldn't otherwise be transformed by Rollup and would lead to issues like [this one](https://github.com/rollup/rollup-plugin-typescript/issues/28)
8634. Use `const enums` and all other files that will require type information.
864
865#### When combined with Babel, what does TypeScript do, and what does Babel do?
866
867First, TypeScript will be used for:
868
8691. Reporting diagnostics.
8702. Emitting TypeScript declaration (`.d.ts`) files and TypeScript declaration map (`.d.ts.map`) files.
8713. Removing TypeScript-specific features such as types, type-only imports, enums, and TypeScript decorators.
872
873Babel will then be used for all other syntax transformation from then on, depending on the combination of default, provided, and forced presets and plugins.
874
875#### When combined with swc, what does TypeScript do, and what does Babel do?
876
877[This FAQ answer applies to swc as well](#when-combined-with-babel-what-does-typescript-do-and-what-does-babel-do).
878
879Additionally, if swc is instructed to apply minification, it will do that for every generated chunk, rather than on a per-file basis, to ensure the most optimal optimizations and smallest possible output.
880
881#### Why is @babel/plugin-transform-runtime and tslib included by default?
882
883[See this explainer](./documentation/explainer/why_is_babel-plugin-transform-runtime_and_tslib_included_by_default.md).
884
885## Starter templates
886
887The following is an evolving list of starter templates for new projects using Rollup, TypeScript, and `rollup-plugin-ts` that you can take a look at and draw inspiration from.
888
889- [Library with CommonJS and ESM output and TypeScript declarations](https://repl.it/@wessberg/rollup-plugin-ts-library-cjs-esm-declarations-1)
890
891<!-- SHADOW_SECTION_LICENSE_START -->
892
893## License
894
895MIT © [Frederik Wessberg](mailto:frederikwessberg@hotmail.com) ([@FredWessberg](https://twitter.com/FredWessberg)) ([Website](https://github.com/wessberg))
896
897<!-- SHADOW_SECTION_LICENSE_END -->