UNPKG

12 kBMarkdownView Raw
1[npm]: https://img.shields.io/npm/v/@rollup/plugin-typescript
2[npm-url]: https://www.npmjs.com/package/@rollup/plugin-typescript
3[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-typescript
4[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-typescript
5
6[![npm][npm]][npm-url]
7[![size][size]][size-url]
8[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
9
10# @rollup/plugin-typescript
11
12🍣 A Rollup plugin for seamless integration between Rollup and Typescript.
13
14## Requirements
15
16This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v2.14.0+. This plugin also requires at least [TypeScript 3.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html).
17
18## Install
19
20Using npm:
21
22```console
23npm install @rollup/plugin-typescript --save-dev
24```
25
26Note that both `typescript` and `tslib` are peer dependencies of this plugin that need to be installed separately.
27
28## Why?
29
30See [@rollup/plugin-babel](https://github.com/rollup/plugins/tree/master/packages/babel).
31
32## Usage
33
34Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
35
36```js
37// rollup.config.js
38import typescript from '@rollup/plugin-typescript';
39
40export default {
41 input: 'src/index.ts',
42 output: {
43 dir: 'output',
44 format: 'cjs'
45 },
46 plugins: [typescript()]
47};
48```
49
50Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#command-line-reference) or the [API](https://www.rollupjs.org/guide/en/#javascript-api).
51
52## Options
53
54The plugin loads any [`compilerOptions`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) from the `tsconfig.json` file by default. Passing options to the plugin directly overrides those options:
55
56```js
57...
58export default {
59 input: './main.ts',
60 plugins: [
61 typescript({ compilerOptions: {lib: ["es5", "es6", "dom"], target: "es5"}})
62 ]
63}
64```
65
66The following options are unique to `@rollup/plugin-typescript`:
67
68### `exclude`
69
70Type: `String` | `Array[...String]`<br>
71Default: `null`
72
73A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. By default no files are ignored.
74
75### `include`
76
77Type: `String` | `Array[...String]`<br>
78Default: `null`
79
80A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should operate on. By default all `.ts` and `.tsx` files are targeted.
81
82### `filterRoot`
83
84Type: `String` | `Boolean`<br>
85Default: `rootDir` ?? `tsConfig.compilerOptions.rootDir` ?? `process.cwd()`
86
87Optionally resolves the include and exclude patterns against a directory other than `process.cwd()`. If a String is specified, then the value will be used as the base directory. Relative paths will be resolved against `process.cwd()` first. If `false`, then the patterns will not be resolved against any directory.
88
89By default, patterns resolve against the rootDir set in your TS config file.
90
91This can fix plugin errors when parsing files outside the current working directory (process.cwd()).
92
93### `tsconfig`
94
95Type: `String` | `Boolean`<br>
96Default: `true`
97
98When set to false, ignores any options specified in the config file. If set to a string that corresponds to a file path, the specified file will be used as config file.
99
100### `typescript`
101
102Type: `import('typescript')`<br>
103Default: _peer dependency_
104
105Overrides the TypeScript module used for transpilation.
106
107```js
108typescript({
109 typescript: require('some-fork-of-typescript')
110});
111```
112
113### `tslib`
114
115Type: `String`<br>
116Default: _peer dependency_
117
118Overrides the injected TypeScript helpers with a custom version.
119
120```js
121typescript({
122 tslib: require.resolve('some-fork-of-tslib')
123});
124```
125
126### `transformers`
127
128Type: `{ [before | after | afterDeclarations]: TransformerFactory[] } | ((program: ts.Program) => ts.CustomTransformers)`<br>
129Default: `undefined`
130
131Allows registration of TypeScript custom transformers at any of the supported stages:
132
133- **before**: transformers will execute before the TypeScript's own transformers on raw TypeScript files
134- **after**: transformers will execute after the TypeScript transformers on transpiled code
135- **afterDeclarations**: transformers will execute after declaration file generation allowing to modify existing declaration files
136
137Supported transformer factories:
138
139- all **built-in** TypeScript custom transformer factories:
140
141 - `import('typescript').TransformerFactory` annotated **TransformerFactory** bellow
142 - `import('typescript').CustomTransformerFactory` annotated **CustomTransformerFactory** bellow
143
144- **ProgramTransformerFactory** represents a transformer factory allowing the resulting transformer to grab a reference to the **Program** instance
145
146 ```js
147 {
148 type: 'program',
149 factory: (program: Program) => TransformerFactory | CustomTransformerFactory
150 }
151 ```
152
153- **TypeCheckerTransformerFactory** represents a transformer factory allowing the resulting transformer to grab a reference to the **TypeChecker** instance
154 ```js
155 {
156 type: 'typeChecker',
157 factory: (typeChecker: TypeChecker) => TransformerFactory | CustomTransformerFactory
158 }
159 ```
160
161```js
162typescript({
163 transformers: {
164 before: [
165 {
166 // Allow the transformer to get a Program reference in it's factory
167 type: 'program',
168 factory: (program) => {
169 return ProgramRequiringTransformerFactory(program);
170 }
171 },
172 {
173 type: 'typeChecker',
174 factory: (typeChecker) => {
175 // Allow the transformer to get a TypeChecker reference in it's factory
176 return TypeCheckerRequiringTransformerFactory(typeChecker);
177 }
178 }
179 ],
180 after: [
181 // You can use normal transformers directly
182 require('custom-transformer-based-on-Context')
183 ],
184 afterDeclarations: [
185 // Or even define in place
186 function fixDeclarationFactory(context) {
187 return function fixDeclaration(source) {
188 function visitor(node) {
189 // Do real work here
190
191 return ts.visitEachChild(node, visitor, context);
192 }
193
194 return ts.visitEachChild(source, visitor, context);
195 };
196 }
197 ]
198 }
199});
200```
201
202Alternatively, the transformers can be created inside a factory.
203
204Supported transformer factories:
205
206- all **built-in** TypeScript custom transformer factories:
207
208 - `import('typescript').TransformerFactory` annotated **TransformerFactory** bellow
209 - `import('typescript').CustomTransformerFactory` annotated **CustomTransformerFactory** bellow
210
211The example above could be written like this:
212
213```js
214typescript({
215 transformers: function (program) {
216 return {
217 before: [
218 ProgramRequiringTransformerFactory(program),
219 TypeCheckerRequiringTransformerFactory(program.getTypeChecker())
220 ],
221 after: [
222 // You can use normal transformers directly
223 require('custom-transformer-based-on-Context')
224 ],
225 afterDeclarations: [
226 // Or even define in place
227 function fixDeclarationFactory(context) {
228 return function fixDeclaration(source) {
229 function visitor(node) {
230 // Do real work here
231
232 return ts.visitEachChild(node, visitor, context);
233 }
234
235 return ts.visitEachChild(source, visitor, context);
236 };
237 }
238 ]
239 };
240 }
241});
242```
243
244### `cacheDir`
245
246Type: `String`<br>
247Default: _.rollup.cache_
248
249When compiling with `incremental` or `composite` options the plugin will
250store compiled files in this folder. This allows the use of incremental
251compilation.
252
253```js
254typescript({
255 cacheDir: '.rollup.tscache'
256});
257```
258
259### `noForceEmit`
260
261Type: `Boolean`<br>
262Default: `false`
263
264Earlier version of `@rollup/plugin-typescript` required that the `compilerOptions` `noEmit` and `emitDeclarationOnly` both false to guarantee that source code was fed into the next plugin/output. This is no longer true. This option disables the plugin forcing the values of those options and instead defers to the values set in `tsconfig.json`.
265
266`noForceEmit` can be very useful if you use with `@rollup/plugin-babel` and `@babel/preset-typescript`. Having `@rollup/plugin-typescript` only do typechecking / declarations with `"emitDeclarationOnly": true` while deferring to `@rollup/plugin-babel` for transpilation can dramatically reduce `rollup` build times for large projects.
267
268### Typescript compiler options
269
270Some of Typescript's [CompilerOptions](https://www.typescriptlang.org/docs/handbook/compiler-options.html) affect how Rollup builds files.
271
272#### `noEmitOnError`
273
274Type: `Boolean`<br>
275Default: `false`
276
277If a type error is detected, the Rollup build is aborted when this option is set to true.
278
279#### `files`, `include`, `exclude`
280
281Type: `Array[...String]`<br>
282Default: `[]`
283
284Declaration files are automatically included if they are listed in the `files` field in your `tsconfig.json` file. Source files in these fields are ignored as Rollup's configuration is used instead.
285
286#### Ignored options
287
288These compiler options are ignored by Rollup:
289
290- `noEmitHelpers`, `importHelpers`: The `tslib` helper module always must be used.
291- `noEmit`, `emitDeclarationOnly`: Typescript needs to emit code for the plugin to work with.
292 - _Note: While this was true for early iterations of `@rollup/plugin-typescript`, it is no longer. To override this behavior, and defer to `tsconfig.json` for these options, see the [`noForceEmit`](#noForceEmit) option_
293- `noResolve`: Preventing Typescript from resolving code may break compilation
294
295### Importing CommonJS
296
297Though it is not recommended, it is possible to configure this plugin to handle imports of CommonJS files from TypeScript. For this, you need to specify `CommonJS` as the module format and add [`@rollup/plugin-commonjs`](https://github.com/rollup/plugins/tree/master/packages/commonjs) to transpile the CommonJS output generated by TypeScript to ES Modules so that rollup can process it.
298
299```js
300// rollup.config.js
301import typescript from '@rollup/plugin-typescript';
302import commonjs from '@rollup/plugin-commonjs';
303
304export default {
305 input: './main.ts',
306 plugins: [
307 typescript({ compilerOptions: { module: 'CommonJS' } }),
308 commonjs({ extensions: ['.js', '.ts'] }) // the ".ts" extension is required
309 ]
310};
311```
312
313Note that this will often result in less optimal output.
314
315### Preserving JSX output
316
317Whenever choosing to preserve JSX output to be further consumed by another transform step via `tsconfig` `compilerOptions` by setting `jsx: 'preserve'` or [overriding options](#options), please bear in mind that, by itself, this plugin won't be able to preserve JSX output, usually failing with:
318
319```sh
320[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
321file.tsx (1:15)
3221: export default <span>Foobar</span>
323 ^
324```
325
326To prevent that, make sure to use the acorn plugin, namely `acorn-jsx`, which will make Rollup's parser acorn handle JSX tokens. (See https://rollupjs.org/guide/en/#acorninjectplugins)
327
328After adding `acorn-jsx` plugin, your Rollup config would look like the following, correctly preserving your JSX output.
329
330```js
331import jsx from 'acorn-jsx';
332import typescript from '@rollup/plugin-typescript';
333
334export default {
335 // … other options …
336 acornInjectPlugins: [jsx()],
337 plugins: [typescript({ compilerOptions: { jsx: 'preserve' } })]
338};
339```
340
341### Faster compiling
342
343Previous versions of this plugin used Typescript's `transpileModule` API, which is faster but does not perform typechecking and does not support cross-file features like `const enum`s and emit-less types. If you want this behaviour, you can use [@rollup/plugin-sucrase](https://github.com/rollup/plugins/tree/master/packages/sucrase) instead.
344
345## Meta
346
347[CONTRIBUTING](/.github/CONTRIBUTING.md)
348
349[LICENSE (MIT)](/LICENSE)