UNPKG

30.5 kBMarkdownView Raw
1# TypeScript loader for webpack
2
3[![npm version](https://img.shields.io/npm/v/ts-loader.svg)](https://www.npmjs.com/package/ts-loader)
4![GitHub build)](https://github.com/TypeStrong/ts-loader/workflows/Continuous%20Integration%20(build%20and%20test)/badge.svg)
5[![Travis build](https://travis-ci.org/TypeStrong/ts-loader.svg?branch=master)](https://travis-ci.org/TypeStrong/ts-loader)
6[![Downloads](http://img.shields.io/npm/dm/ts-loader.svg)](https://npmjs.org/package/ts-loader)
7[![node version](https://img.shields.io/node/v/ts-loader.svg)](https://www.npmjs.com/package/ts-loader)
8[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
9
10<br />
11<p align="center">
12 <h3 align="center">ts-loader</h3>
13
14 <p align="center">
15 This is the TypeScript loader for webpack.
16 <br />
17 <br />
18 <a href="https://github.com/TypeStrong/ts-loader#installation">Installation</a>
19 ·
20 <a href="https://github.com/TypeStrong/ts-loader/issues">Report Bug</a>
21 ·
22 <a href="https://github.com/TypeStrong/ts-loader/issues">Request Feature</a>
23 </p>
24</p>
25
26## Table of Contents
27
28<!-- toc -->
29
30- [Getting Started](#getting-started)
31 * [Installation](#installation)
32 * [Running](#running)
33 * [Examples](#examples)
34 * [Faster Builds](#faster-builds)
35 * [Yarn Plug’n’Play](#yarn-plugnplay)
36 * [Babel](#babel)
37 * [Parallelising Builds](#parallelising-builds)
38 * [Compatibility](#compatibility)
39 * [Configuration](#configuration)
40 + [`devtool` / sourcemaps](#devtool--sourcemaps)
41 * [Code Splitting and Loading Other Resources](#code-splitting-and-loading-other-resources)
42 * [Declarations (.d.ts)](#declarations-dts)
43 * [Failing the build on TypeScript compilation error](#failing-the-build-on-typescript-compilation-error)
44 * [`baseUrl` / `paths` module resolution](#baseurl--paths-module-resolution)
45 * [Options](#options)
46 * [Loader Options](#loader-options)
47 + [transpileOnly](#transpileonly)
48 + [happyPackMode](#happypackmode)
49 + [resolveModuleName and resolveTypeReferenceDirective](#resolvemodulename-and-resolvetypereferencedirective)
50 + [getCustomTransformers](#getcustomtransformers)
51 + [logInfoToStdOut](#loginfotostdout)
52 + [logLevel](#loglevel)
53 + [silent](#silent)
54 + [ignoreDiagnostics](#ignorediagnostics)
55 + [reportFiles](#reportfiles)
56 + [compiler](#compiler)
57 + [configFile](#configfile)
58 + [colors](#colors)
59 + [errorFormatter](#errorformatter)
60 + [compilerOptions](#compileroptions)
61 + [instance](#instance)
62 + [appendTsSuffixTo](#appendtssuffixto)
63 + [appendTsxSuffixTo](#appendtsxsuffixto)
64 + [onlyCompileBundledFiles](#onlycompilebundledfiles)
65 + [allowTsInNodeModules](#allowtsinnodemodules)
66 + [context](#context)
67 + [experimentalFileCaching](#experimentalfilecaching)
68 + [projectReferences](#projectreferences)
69 * [Usage with webpack watch](#usage-with-webpack-watch)
70 * [Hot Module replacement](#hot-module-replacement)
71- [Contributing](#contributing)
72- [License](#license)
73
74<!-- tocstop -->
75
76## Getting Started
77
78### Installation
79
80```
81yarn add ts-loader --dev
82```
83
84or
85
86```
87npm install ts-loader --save-dev
88```
89
90You will also need to install TypeScript if you have not already.
91
92```
93yarn add typescript --dev
94```
95
96or
97
98```
99npm install typescript --save-dev
100```
101
102### Running
103
104Use webpack like normal, including `webpack --watch` and `webpack-dev-server`, or through another
105build system using the [Node.js API](https://webpack.js.org/api/node/).
106
107### Examples
108
109We have a number of example setups to accommodate different workflows. Our examples can be found [here](examples/).
110
111We probably have more examples than we need. That said, here's a good way to get started:
112
113- I want the simplest setup going. Use "[vanilla](examples/vanilla)" `ts-loader`
114- I want the fastest compilation that's available. Use [fork-ts-checker-webpack-plugin](https://github.com/Realytics/fork-ts-checker-webpack-plugin). It performs type checking in a separate process with `ts-loader` just handling transpilation.
115
116### Faster Builds
117
118As your project becomes bigger, compilation time increases linearly. It's because typescript's semantic checker has to inspect all files on every rebuild. The simple solution is to disable it by using the `transpileOnly: true` option, but doing so leaves you without type checking and *will not output declaration files*.
119
120You probably don't want to give up type checking; that's rather the point of TypeScript. So what you can do is use the [fork-ts-checker-webpack-plugin](https://github.com/Realytics/fork-ts-checker-webpack-plugin). It runs the type checker on a separate process, so your build remains fast thanks to `transpileOnly: true` but you still have the type checking. Also, the plugin has several optimizations to make incremental type checking faster (AST cache, multiple workers).
121
122If you'd like to see a simple setup take a look at [our simple example](examples/fork-ts-checker-webpack-plugin/). For a more complex setup take a look at our [more involved example](examples/react-babel-karma-gulp).
123
124### Yarn Plug’n’Play
125
126`ts-loader` supports [Yarn Plug’n’Play](https://yarnpkg.com/en/docs/pnp). The recommended way to integrate is using the [pnp-webpack-plugin](https://github.com/arcanis/pnp-webpack-plugin#ts-loader-integration).
127
128### Babel
129
130`ts-loader` works very well in combination with [babel](https://babeljs.io/) and [babel-loader](https://github.com/babel/babel-loader). There is an [example](https://github.com/Microsoft/TypeScriptSamples/tree/master/react-flux-babel-karma) of this in the official [TypeScript Samples](https://github.com/Microsoft/TypeScriptSamples). Alternatively take a look at our own [example](examples/react-babel-karma-gulp).
131
132### Parallelising Builds
133
134It's possible to parallelise your builds. Historically this was useful from a performance perspective with webpack 2 / 3. [With webpack 4+ there appears to be significantly less benefit and perhaps even cost.](https://blog.johnnyreilly.com/2018/12/you-might-not-need-thread-loader.html)
135
136But if that's what you want to do, there's two ways to achieve this: [happypack](https://github.com/amireh/happypack) and [thread-loader](https://github.com/webpack-contrib/thread-loader). Both should be used in combination with [fork-ts-checker-webpack-plugin](https://github.com/Realytics/fork-ts-checker-webpack-plugin) for typechecking.)
137
138To read more, look at [this post](https://medium.com/webpack/typescript-webpack-super-pursuit-mode-83cc568dea79) by [@johnny_reilly](https://twitter.com/johnny_reilly) on the webpack publication channel.
139
140If you'd like find out further ways to improve your build using the watch API then take a look at [this post](https://medium.com/@kenneth_chau/speeding-up-webpack-typescript-incremental-builds-by-7x-3912ba4c1d15) by [@kenneth_chau](https://twitter.com/kenneth_chau).
141
142### Compatibility
143
144* TypeScript: 3.6.3+
145* webpack: 4.x+ (please use `ts-loader` 3.x if you need webpack 2 or 3 support)
146* node: 6.11.5 minimum (aligned with webpack 4)
147
148A full test suite runs each night (and on each pull request). It runs both on [Linux](https://travis-ci.org/TypeStrong/ts-loader) and [Windows](https://ci.appveyor.com/project/JohnReilly/ts-loader), testing `ts-loader` against major releases of TypeScript. The test suite also runs against TypeScript@next (because we want to use it as much as you do).
149
150If you become aware of issues not caught by the test suite then please let us know. Better yet, write a test and submit it in a PR!
151
152### Configuration
153
1541. Create or update `webpack.config.js` like so:
155
156 ```javascript
157 module.exports = {
158 mode: "development",
159 devtool: "inline-source-map",
160 entry: "./app.ts",
161 output: {
162 filename: "bundle.js"
163 },
164 resolve: {
165 // Add `.ts` and `.tsx` as a resolvable extension.
166 extensions: [".ts", ".tsx", ".js"]
167 },
168 module: {
169 rules: [
170 // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
171 { test: /\.tsx?$/, loader: "ts-loader" }
172 ]
173 }
174 };
175 ```
176
1772. Add a [`tsconfig.json`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) file. (The one below is super simple; but you can tweak this to your hearts desire)
178
179 ```json
180 {
181 "compilerOptions": {
182 "sourceMap": true
183 }
184 }
185 ```
186
187The [tsconfig.json](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html) file controls
188TypeScript-related options so that your IDE, the `tsc` command, and this loader all share the
189same options.
190
191#### `devtool` / sourcemaps
192
193If you want to be able to debug your original source then you can thanks to the magic of sourcemaps. There are 2 steps to getting this set up with `ts-loader` and webpack.
194
195First, for `ts-loader` to produce **sourcemaps**, you will need to set the [tsconfig.json](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html) option as `"sourceMap": true`.
196
197Second, you need to set the `devtool` option in your `webpack.config.js` to support the type of sourcemaps you want. To make your choice have a read of the [`devtool` webpack docs](https://webpack.js.org/configuration/devtool/). You may be somewhat daunted by the choice available. You may also want to vary the sourcemap strategy depending on your build environment. Here are some example strategies for different environments:
198
199* `devtool: 'inline-source-map'` - Solid sourcemap support; the best "all-rounder". Works well with karma-webpack (not all strategies do)
200* `devtool: 'cheap-module-eval-source-map'` - Best support for sourcemaps whilst debugging.
201* `devtool: 'source-map'` - Approach that plays well with UglifyJsPlugin; typically you might use this in Production
202
203### Code Splitting and Loading Other Resources
204
205Loading css and other resources is possible but you will need to make sure that
206you have defined the `require` function in a [declaration file](https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html).
207
208```typescript
209declare var require: {
210 <T>(path: string): T;
211 (paths: string[], callback: (...modules: any[]) => void): void;
212 ensure: (
213 paths: string[],
214 callback: (require: <T>(path: string) => T) => void
215 ) => void;
216};
217```
218
219Then you can simply require assets or chunks per the [webpack documentation](https://webpack.js.org/guides/code-splitting/).
220
221```javascript
222require("!style!css!./style.css");
223```
224
225The same basic process is required for code splitting. In this case, you `import` modules you need but you
226don't directly use them. Instead you require them at [split points](https://webpack.js.org/guides/code-splitting/). See [this example](test/comparison-tests/codeSplitting) and [this example](test/comparison-tests/es6codeSplitting) for more details.
227
228[TypeScript 2.4 provides support for ECMAScript's new `import()` calls. These calls import a module and return a promise to that module.](https://blogs.msdn.microsoft.com/typescript/2017/06/12/announcing-typescript-2-4-rc/) This is also supported in webpack - details on usage can be found [here](https://webpack.js.org/guides/code-splitting-async/#dynamic-import-import-). Happy code splitting!
229
230### Declarations (.d.ts)
231
232To output a built .d.ts file, you can set `"declaration": true` in your tsconfig, and use the [DeclarationBundlerPlugin](https://www.npmjs.com/package/declaration-bundler-webpack-plugin) in your webpack config.
233
234### Failing the build on TypeScript compilation error
235
236The build **should** fail on TypeScript compilation errors as of webpack 2. If for some reason it does not, you can use the [webpack-fail-plugin](https://www.npmjs.com/package/webpack-fail-plugin).
237
238For more background have a read of [this issue](https://github.com/TypeStrong/ts-loader/issues/108).
239
240### `baseUrl` / `paths` module resolution
241
242If you want to resolve modules according to `baseUrl` and `paths` in your `tsconfig.json` then you can use the [tsconfig-paths-webpack-plugin](https://www.npmjs.com/package/tsconfig-paths-webpack-plugin) package. For details about this functionality, see the [module resolution documentation](https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url).
243
244This feature requires webpack 2.1+ and TypeScript 2.0+. Use the config below or check the [package](https://github.com/dividab/tsconfig-paths-webpack-plugin/blob/master/README.md) for more information on usage.
245
246```javascript
247const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
248
249module.exports = {
250 ...
251 resolve: {
252 plugins: [new TsconfigPathsPlugin({ configFile: "./path/to/tsconfig.json" })]
253 }
254 ...
255}
256```
257
258### Options
259
260There are two types of options: TypeScript options (aka "compiler options") and loader options. TypeScript options should be set using a tsconfig.json file. Loader options can be specified through the `options` property in the webpack configuration:
261
262```javascript
263module.exports = {
264 ...
265 module: {
266 rules: [
267 {
268 test: /\.tsx?$/,
269 use: [
270 {
271 loader: 'ts-loader',
272 options: {
273 transpileOnly: true
274 }
275 }
276 ]
277 }
278 ]
279 }
280}
281```
282
283### Loader Options
284
285#### transpileOnly
286| Type | Default Value |
287|------|--------------|
288| `boolean` | `false`|
289
290If you want to speed up compilation significantly you can set this flag.
291However, many of the benefits you get from static type checking between different dependencies in your application will be lost. `transpileOnly` will *not* speed up compilation of project references.
292
293It's advisable to use `transpileOnly` alongside the [fork-ts-checker-webpack-plugin](https://github.com/Realytics/fork-ts-checker-webpack-plugin) to get full type checking again. To see what this looks like in practice then either take a look at [our simple example](examples/fork-ts-checker-webpack-plugin). For a more complex setup take a look at our [more involved example](examples/react-babel-karma-gulp).
294
295If you enable this option, webpack 4 will give you "export not found" warnings any time you re-export a type:
296
297```
298WARNING in ./src/bar.ts
2991:0-34 "export 'IFoo' was not found in './foo'
300 @ ./src/bar.ts
301 @ ./src/index.ts
302```
303
304The reason this happens is that when typescript doesn't do a full type check, it does not have enough information to determine whether an imported name is a type or not, so when the name is then exported, typescript has no choice but to emit the export. Fortunately, the extraneous export should not be harmful, so you can just suppress these warnings:
305
306```javascript
307module.exports = {
308 ...
309 stats: {
310 warningsFilter: /export .* was not found in/
311 }
312}
313```
314
315#### happyPackMode
316| Type | Default Value |
317|------|--------------|
318| `boolean` | `false`|
319
320If you're using [HappyPack](https://github.com/amireh/happypack) or [thread-loader](https://github.com/webpack-contrib/thread-loader) to parallise your builds then you'll need to set this to `true`. This implicitly sets `*transpileOnly*` to `true` and **WARNING!** stops registering **_all_** errors to webpack.
321
322It's advisable to use this with the [fork-ts-checker-webpack-plugin](https://github.com/Realytics/fork-ts-checker-webpack-plugin) to get full type checking again. To see what this looks like in practice then either take a look at [our simple thread-loader example](examples/thread-loader). **_IMPORTANT_**: If you are using fork-ts-checker-webpack-plugin alongside HappyPack or thread-loader then ensure you set the `syntactic` diagnostic option like so:
323
324```javascript
325 new ForkTsCheckerWebpackPlugin({
326 typescript: {
327 diagnosticOptions: {
328 semantic: true,
329 syntactic: true,
330 },
331 },
332 })
333```
334
335This will ensure that the plugin checks for both syntactic errors (eg `const array = [{} {}];`) and semantic errors (eg `const x: number = '1';`). By default the plugin only checks for semantic errors (as when used with `ts-loader` in `transpileOnly` mode, `ts-loader` will still report syntactic errors).
336
337Also, if you are using `thread-loader` in watch mode, remember to set `poolTimeout: Infinity` so workers don't die.
338
339#### resolveModuleName and resolveTypeReferenceDirective
340
341These options should be functions which will be used to resolve the import statements and the `<reference types="...">` directives instead of the default TypeScript implementation. It's not intended that these will typically be used by a user of `ts-loader` - they exist to facilitate functionality such as [Yarn Plug’n’Play](https://yarnpkg.com/en/docs/pnp).
342
343#### getCustomTransformers
344| Type |
345|------|
346| ` (program: Program) => { before?: TransformerFactory<SourceFile>[]; after?: TransformerFactory<SourceFile>[]; } ` |
347
348Provide custom transformers - only compatible with TypeScript 2.3+ (and 2.4 if using `transpileOnly` mode). For example usage take a look at [typescript-plugin-styled-components](https://github.com/Igorbek/typescript-plugin-styled-components) or our [test](test/comparison-tests/customTransformer).
349
350You can also pass a path string to locate a js module file which exports the function described above, this useful especially in `happyPackMode`. (Because forked processes cannot serialize functions see more at [related issue](https://github.com/Igorbek/typescript-plugin-styled-components/issues/6#issue-303387183))
351
352#### logInfoToStdOut
353| Type | Default Value |
354|------|--------------|
355| `boolean` | `false`|
356
357This is important if you read from stdout or stderr and for proper error handling.
358The default value ensures that you can read from stdout e.g. via pipes or you use webpack -j to generate json output.
359
360#### logLevel
361| Type | Default Value |
362|------|--------------|
363| `string` | `warn` |
364
365Can be `info`, `warn` or `error` which limits the log output to the specified log level.
366Beware of the fact that errors are written to stderr and everything else is written to stderr (or stdout if logInfoToStdOut is true).
367
368#### silent
369| Type | Default Value |
370|------|--------------|
371| `boolean` | `false`|
372
373If `true`, no console.log messages will be emitted. Note that most error
374messages are emitted via webpack which is not affected by this flag.
375
376#### ignoreDiagnostics
377| Type | Default Value |
378|------|--------------|
379| `number[]` | `[]`|
380
381You can squelch certain TypeScript errors by specifying an array of diagnostic
382codes to ignore.
383
384#### reportFiles
385| Type | Default Value |
386|------|--------------|
387| `string[]` | `[]`|
388
389Only report errors on files matching these glob patterns.
390
391```javascript
392 // in webpack.config.js
393 {
394 test: /\.ts$/,
395 loader: 'ts-loader',
396 options: { reportFiles: ['src/**/*.{ts,tsx}', '!src/skip.ts'] }
397 }
398```
399
400This can be useful when certain types definitions have errors that are not fatal to your application.
401
402#### compiler
403| Type | Default Value |
404|------|--------------|
405| `string` | `'typescript'`|
406
407Allows use of TypeScript compilers other than the official one. Should be
408set to the NPM name of the compiler, eg [`ntypescript`](https://github.com/basarat/ntypescript).
409
410#### configFile
411| Type | Default Value |
412|------|--------------|
413| `string` | `'tsconfig.json'`|
414
415Allows you to specify where to find the TypeScript configuration file.
416
417You may provide
418
419* just a file name. The loader then will search for the config file of each entry point in the respective entry point's containing folder. If a config file cannot be found there, it will travel up the parent directory chain and look for the config file in those folders.
420* a relative path to the configuration file. It will be resolved relative to the respective `.ts` entry file.
421* an absolute path to the configuration file.
422
423Please note, that if the configuration file is outside of your project directory, you might need to set the `context` option to avoid TypeScript issues (like TS18003).
424In this case the `configFile` should point to the `tsconfig.json` and `context` to the project root.
425
426#### colors
427| Type | Default Value |
428|------|--------------|
429| `boolean` | `true`|
430
431If `false`, disables built-in colors in logger messages.
432
433#### errorFormatter
434| Type | Default Value |
435|------|--------------|
436| `(message: ErrorInfo, colors: boolean) => string` | `undefined`|
437
438By default `ts-loader` formats TypeScript compiler output for an error or a warning in the style:
439
440```
441[tsl] ERROR in myFile.ts(3,14)
442 TS4711: you did something very wrong
443```
444
445If that format is not to your taste you can supply your own formatter using the `errorFormatter` option. Below is a template for a custom error formatter. Please note that the `colors` parameter is an instance of [`chalk`](https://github.com/chalk/chalk) which you can use to color your output. (This instance will respect the `colors` option.)
446
447```javascript
448function customErrorFormatter(error, colors) {
449 const messageColor =
450 error.severity === "warning" ? colors.bold.yellow : colors.bold.red;
451 return (
452 "Does not compute.... " +
453 messageColor(Object.keys(error).map(key => `${key}: ${error[key]}`))
454 );
455}
456```
457
458If the above formatter received an error like this:
459
460```json
461{
462 "code":2307,
463 "severity": "error",
464 "content": "Cannot find module 'components/myComponent2'.",
465 "file":"/.test/errorFormatter/app.ts",
466 "line":2,
467 "character":31
468}
469```
470
471It would produce an error message that said:
472
473```
474Does not compute.... code: 2307,severity: error,content: Cannot find module 'components/myComponent2'.,file: /.test/errorFormatter/app.ts,line: 2,character: 31
475```
476
477And the bit after "Does not compute.... " would be red.
478
479#### compilerOptions
480| Type | Default Value |
481|------|--------------|
482| `object` | `{}`|
483
484Allows overriding TypeScript options. Should be specified in the same format
485as you would do for the `compilerOptions` property in tsconfig.json.
486
487#### instance
488| Type | Default Value |
489|------|--------------|
490| `string` | `TODO`|
491
492Advanced option to force files to go through different instances of the
493TypeScript compiler. Can be used to force segregation between different parts
494of your code.
495
496#### appendTsSuffixTo
497| Type | Default Value |
498|------|--------------|
499| `(RegExp \| string)[]` | `[]`|
500
501#### appendTsxSuffixTo
502| Type | Default Value |
503|------|--------------|
504| `(RegExp \| string)[]` | `[]`|
505
506A list of regular expressions to be matched against filename. If filename matches one of the regular expressions, a `.ts` or `.tsx` suffix will be appended to that filename.
507If you're using [HappyPack](https://github.com/amireh/happypack) or [thread-loader](https://github.com/webpack-contrib/thread-loader) with `ts-loader`, you need use the `string` type for the regular expressions, not `RegExp` object.
508
509```js
510// change this:
511{ appendTsSuffixTo: [/\.vue$/] }
512// to:
513{ appendTsSuffixTo: ['\\.vue$'] }
514```
515
516
517This is useful for `*.vue` [file format](https://vuejs.org/v2/guide/single-file-components.html) for now. (Probably will benefit from the new single file format in the future.)
518
519Example:
520
521webpack.config.js:
522
523```javascript
524module.exports = {
525 entry: "./index.vue",
526 output: { filename: "bundle.js" },
527 resolve: {
528 extensions: [".ts", ".vue"]
529 },
530 module: {
531 rules: [
532 { test: /\.vue$/, loader: "vue-loader" },
533 {
534 test: /\.ts$/,
535 loader: "ts-loader",
536 options: { appendTsSuffixTo: [/\.vue$/] }
537 }
538 ]
539 }
540};
541```
542
543index.vue
544
545```vue
546<template><p>hello {{msg}}</p></template>
547<script lang="ts">
548export default {
549 data(): Object {
550 return {
551 msg: "world"
552 };
553 }
554};
555</script>
556```
557
558We can handle `.tsx` by quite similar way:
559
560webpack.config.js:
561
562```javascript
563module.exports = {
564 entry: './index.vue',
565 output: { filename: 'bundle.js' },
566 resolve: {
567 extensions: ['.ts', '.tsx', '.vue', '.vuex']
568 },
569 module: {
570 rules: [
571 { test: /\.vue$/, loader: 'vue-loader',
572 options: {
573 loaders: {
574 ts: 'ts-loader',
575 tsx: 'babel-loader!ts-loader',
576 }
577 }
578 },
579 { test: /\.ts$/, loader: 'ts-loader', options: { appendTsSuffixTo: [/TS\.vue$/] } }
580 { test: /\.tsx$/, loader: 'babel-loader!ts-loader', options: { appendTsxSuffixTo: [/TSX\.vue$/] } }
581 ]
582 }
583}
584```
585
586tsconfig.json (set `jsx` option to `preserve` to let babel handle jsx)
587
588```json
589{
590 "compilerOptions": {
591 "jsx": "preserve"
592 }
593}
594```
595
596index.vue
597
598```vue
599<script lang="tsx">
600export default {
601 functional: true,
602 render(h, c) {
603 return (<div>Content</div>);
604 }
605}
606</script>
607```
608
609Or if you want to use only tsx, just use the `appendTsxSuffixTo` option only:
610
611```javascript
612 { test: /\.ts$/, loader: 'ts-loader' }
613 { test: /\.tsx$/, loader: 'babel-loader!ts-loader', options: { appendTsxSuffixTo: [/\.vue$/] } }
614```
615
616#### onlyCompileBundledFiles
617| Type | Default Value |
618|------|--------------|
619| `boolean` | `false`|
620
621The default behavior of `ts-loader` is to act as a drop-in replacement for the `tsc` command,
622so it respects the `include`, `files`, and `exclude` options in your `tsconfig.json`, loading
623any files specified by those options. The `onlyCompileBundledFiles` option modifies this behavior,
624loading only those files that are actually bundled by webpack, as well as any `.d.ts` files included
625by the `tsconfig.json` settings. `.d.ts` files are still included because they may be needed for
626compilation without being explicitly imported, and therefore not picked up by webpack.
627
628#### allowTsInNodeModules
629| Type | Default Value |
630|------|--------------|
631| `boolean` | `false`|
632
633By default, `ts-loader` will not compile `.ts` files in `node_modules`.
634You should not need to recompile `.ts` files there, but if you really want to, use this option.
635Note that this option acts as a *whitelist* - any modules you desire to import must be included in
636the `"files"` or `"include"` block of your project's `tsconfig.json`.
637
638See: [https://github.com/Microsoft/TypeScript/issues/12358](https://github.com/Microsoft/TypeScript/issues/12358)
639
640```javascript
641 // in webpack.config.js
642 {
643 test: /\.ts$/,
644 loader: 'ts-loader',
645 options: { allowTsInNodeModules: true }
646 }
647```
648
649And in your `tsconfig.json`:
650
651```json
652 {
653 "include": [
654 "node_modules/whitelisted_module.ts"
655 ],
656 "files": [
657 "node_modules/my_module/whitelisted_file.ts"
658 ]
659 }
660```
661
662#### context
663| Type | Default Value |
664|------|--------------|
665| `string` | `undefined`|
666
667If set, will parse the TypeScript configuration file with given **absolute path** as base path.
668Per default the directory of the configuration file is used as base path. Relative paths in the configuration
669file are resolved with respect to the base path when parsed. Option `context` allows to set option
670`configFile` to a path other than the project root (e.g. a NPM package), while the base path for `ts-loader`
671can remain the project root.
672
673Keep in mind that **not** having a `tsconfig.json` in your project root can cause different behaviour between `ts-loader` and `tsc`.
674When using editors like `VS Code` it is advised to add a `tsconfig.json` file to the root of the project and extend the config file
675referenced in option `configFile`. For more information please [read the PR](https://github.com/TypeStrong/ts-loader/pull/681) that
676is the base and [read the PR](https://github.com/TypeStrong/ts-loader/pull/688) that contributed this option.
677
678webpack:
679
680```javascript
681{
682 loader: require.resolve('ts-loader'),
683 options: {
684 context: __dirname,
685 configFile: require.resolve('ts-config-react-app')
686 }
687}
688```
689
690Extending `tsconfig.json`:
691
692```json
693{ "extends": "./node_modules/ts-config-react-app/index" }
694```
695
696Note that changes in the extending file while not be respected by `ts-loader`. Its purpose is to satisfy the code editor.
697
698#### experimentalFileCaching
699| Type | Default Value |
700|------|--------------|
701| `boolean` | `true`|
702
703By default whenever the TypeScript compiler needs to check that a file/directory exists or resolve symlinks it makes syscalls. It does not cache the result of these operations and this may result in many syscalls with the same arguments ([see comment](https://github.com/TypeStrong/ts-loader/issues/825#issue-354725524) with example).
704In some cases it may produce performance degradation.
705
706This flag enables caching for some FS-functions like `fileExists`, `realpath` and `directoryExists` for TypeScript compiler. Note that caches are cleared between compilations.
707
708#### projectReferences
709| Type | Default Value |
710|------|--------------|
711| `boolean` | `false`|
712
713ts-loader has opt-in support for [project references](https://www.typescriptlang.org/docs/handbook/project-references.html). With this configuration option enabled, `ts-loader` will incrementally rebuild upstream projects the same way `tsc --build` does. Otherwise, source files in referenced projects will be treated as if they’re part of the root project.
714
715In order to make use of this option your project needs to be correctly configured to build the project references and then to use them as part of the build. See the [Project References Guide](REFERENCES.md) and the example code in the examples which can be found [here](examples/project-references-example/).
716
717### Usage with webpack watch
718
719Because TS will generate .js and .d.ts files, you should ignore these files, otherwise watchers may go into an infinite watch loop. For example, when using webpack, you may wish to add this to your webpack.conf.js file:
720
721```javascript
722 plugins: [
723 new webpack.WatchIgnorePlugin([
724 /\.js$/,
725 /\.d\.ts$/
726 ])
727 ],
728```
729
730It's worth noting that use of the `LoaderOptionsPlugin` is [only supposed to be a stopgap measure](https://webpack.js.org/plugins/loader-options-plugin/). You may want to look at removing it entirely.
731
732### Hot Module replacement
733
734We do not support HMR as we did not yet work out a reliable way how to set it up.
735
736If you want to give `webpack-dev-server` HMR a try, follow the official [webpack HMR guide](https://webpack.js.org/guides/hot-module-replacement/), then tweak a few config options for `ts-loader`:
737
7381. Set `transpileOnly` to `true` (see [transpileOnly](#transpileonly) for config details and recommendations above).
7392. Inside your HMR acceptance callback function, maybe re-require the module that was replaced.
740
741## Contributing
742
743This is your TypeScript loader! We want you to help make it even better. Please feel free to contribute; see the [contributor's guide](CONTRIBUTING.md) to get started.
744
745## License
746
747MIT License