UNPKG

11.2 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 (v8.0.0+) and Rollup v1.20.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 [minimatch pattern](https://github.com/isaacs/minimatch), 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 [minimatch pattern](https://github.com/isaacs/minimatch), 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[] }`<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
202### `cacheDir`
203
204Type: `String`<br>
205Default: _.rollup.cache_
206
207When compiling with `incremental` or `composite` options the plugin will
208store compiled files in this folder. This allows the use of incremental
209compilation.
210
211```js
212typescript({
213 cacheDir: '.rollup.tscache'
214});
215```
216
217### Typescript compiler options
218
219Some of Typescript's [CompilerOptions](https://www.typescriptlang.org/docs/handbook/compiler-options.html) affect how Rollup builds files.
220
221#### `noEmitOnError`
222
223Type: `Boolean`<br>
224Default: `false`
225
226If a type error is detected, the Rollup build is aborted when this option is set to true.
227
228#### `files`, `include`, `exclude`
229
230Type: `Array[...String]`<br>
231Default: `[]`
232
233Declaration 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.
234
235#### Ignored options
236
237These compiler options are ignored by Rollup:
238
239- `noEmitHelpers`, `importHelpers`: The `tslib` helper module always must be used.
240- `noEmit`, `emitDeclarationOnly`: Typescript needs to emit code for the plugin to work with.
241- `noResolve`: Preventing Typescript from resolving code may break compilation
242
243### Importing CommonJS
244
245Though 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.
246
247```js
248// rollup.config.js
249import typescript from '@rollup/plugin-typescript';
250import commonjs from '@rollup/plugin-commonjs';
251
252export default {
253 input: './main.ts',
254 plugins: [
255 typescript({ compilerOptions: { module: 'CommonJS' } }),
256 commonjs({ extensions: ['.js', '.ts'] }) // the ".ts" extension is required
257 ]
258};
259```
260
261Note that this will often result in less optimal output.
262
263### Preserving JSX output
264
265Whenever 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:
266
267```sh
268[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
269file.tsx (1:15)
2701: export default <span>Foobar</span>
271 ^
272```
273
274To 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)
275
276After adding `acorn-jsx` plugin, your Rollup config would look like the following, correctly preserving your JSX output.
277
278```js
279import jsx from 'acorn-jsx';
280import typescript from '@rollup/plugin-typescript';
281
282export default {
283 // … other options …
284 acornInjectPlugins: [jsx()],
285 plugins: [typescript({ compilerOptions: { jsx: 'preserve' } })]
286};
287```
288
289### Faster compiling
290
291Previous 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.
292
293### Declaration Output With `output.file`
294
295When instructing Rollup to output a specific file name via the `output.file` Rollup configuration, and TypeScript to output declaration files, users may encounter a situation where the declarations are nested improperly. And additionally when attempting to fix the improper nesting via use of `outDir` or `declarationDir` result in further TypeScript errors.
296
297Consider the following `rollup.config.js` file:
298
299```js
300import typescript from '@rollup/plugin-typescript';
301
302export default {
303 input: 'src/index.ts',
304 output: {
305 file: 'dist/index.mjs'
306 },
307 plugins: [typescript({ tsconfig: './tsconfig.json' })]
308};
309```
310
311And accompanying `tsconfig.json` file:
312
313```json
314{
315 "include": ["*"],
316 "compilerOptions": {
317 "outDir": "dist",
318 "declaration": true
319 }
320}
321```
322
323This setup will produce `dist/index.mjs` and `dist/dist/index.d.ts`. To correctly place the declaration file, add an `exclude` setting in `tsconfig` and modify the `declarationDir` setting in `compilerOptions` to resemble:
324
325```json
326{
327 "include": ["*"],
328 "exclude": ["dist"],
329 "compilerOptions": {
330 "outDir": "dist",
331 "declaration": true,
332 "declarationDir": "."
333 }
334}
335```
336
337This will result in the correct output of `dist/index.mjs` and `dist/index.d.ts`.
338
339_For reference, please see the workaround this section is based on [here](https://github.com/microsoft/bistring/commit/7e57116c812ae2c01f383c234f3b447f733b5d0c)_
340
341## Meta
342
343[CONTRIBUTING](/.github/CONTRIBUTING.md)
344
345[LICENSE (MIT)](/LICENSE)