UNPKG

30.4 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[![Linux Build Status](https://travis-ci.org/TypeStrong/ts-loader.svg?branch=master)](https://travis-ci.org/TypeStrong/ts-loader)
5[![Windows Build Status](https://ci.appveyor.com/api/projects/status/bjh0r0d4ckspgkh9/branch/master?svg=true)](https://ci.appveyor.com/project/JohnReilly/ts-loader/branch/master)
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[![Join the chat at https://gitter.im/TypeStrong/ts-loader](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg)](https://gitter.im/TypeStrong/ts-loader)
10
11<br />
12<p align="center">
13 <h3 align="center">ts-loader</h3>
14
15 <p align="center">
16 This is the TypeScript loader for webpack.
17 <br />
18 <br />
19 <a href="https://github.com/TypeStrong/ts-loader/issues">Installation</a>
20 ·
21 <a href="https://github.com/TypeStrong/ts-loader/issues">Report Bug</a>
22 ·
23 <a href="https://github.com/TypeStrong/ts-loader/issues">Request Feature</a>
24 </p>
25</p>
26
27## Table of Contents
28
29<!-- toc -->
30
31- [Getting Started](#getting-started)
32 * [Installation](#installation)
33 * [Running](#running)
34 * [Examples](#examples)
35 * [Faster Builds](#faster-builds)
36 * [Yarn Plug’n’Play](#yarn-plugnplay)
37 * [Babel](#babel)
38 * [Parallelising Builds](#parallelising-builds)
39 * [Compatibility](#compatibility)
40 * [Configuration](#configuration)
41 + [`devtool` / sourcemaps](#devtool--sourcemaps)
42 * [Code Splitting and Loading Other Resources](#code-splitting-and-loading-other-resources)
43 * [Declarations (.d.ts)](#declarations-dts)
44 * [Failing the build on TypeScript compilation error](#failing-the-build-on-typescript-compilation-error)
45 * [`baseUrl` / `paths` module resolution](#baseurl--paths-module-resolution)
46 * [Options](#options)
47 * [Loader Options](#loader-options)
48 + [transpileOnly](#transpileonly)
49 + [happyPackMode](#happypackmode)
50 + [resolveModuleName and resolveTypeReferenceDirective](#resolvemodulename-and-resolvetypereferencedirective)
51 + [getCustomTransformers](#getcustomtransformers)
52 + [logInfoToStdOut](#loginfotostdout)
53 + [logLevel](#loglevel)
54 + [silent](#silent)
55 + [ignoreDiagnostics](#ignorediagnostics)
56 + [reportFiles](#reportfiles)
57 + [compiler](#compiler)
58 + [configFile](#configfile)
59 + [colors](#colors)
60 + [errorFormatter](#errorformatter)
61 + [compilerOptions](#compileroptions)
62 + [instance](#instance)
63 + [appendTsSuffixTo](#appendtssuffixto)
64 + [appendTsxSuffixTo](#appendtsxsuffixto)
65 + [onlyCompileBundledFiles](#onlycompilebundledfiles)
66 + [allowTsInNodeModules](#allowtsinnodemodules)
67 + [context](#context)
68 + [experimentalFileCaching](#experimentalfilecaching)
69 + [projectReferences](#projectreferences)
70 * [Usage with webpack watch](#usage-with-webpack-watch)
71 * [Hot Module replacement](#hot-module-replacement)
72- [Contributing](#contributing)
73- [License](#license)
74
75<!-- tocstop -->
76
77## Getting Started
78
79### Installation
80
81```
82yarn add ts-loader --dev
83```
84
85or
86
87```
88npm install ts-loader --save-dev
89```
90
91You will also need to install TypeScript if you have not already.
92
93```
94yarn add typescript --dev
95```
96
97or
98
99```
100npm install typescript --save-dev
101```
102
103### Running
104
105Use webpack like normal, including `webpack --watch` and `webpack-dev-server`, or through another
106build system using the [Node.js API](https://webpack.js.org/api/node/).
107
108### Examples
109
110We have a number of example setups to accommodate different workflows. Our examples can be found [here](examples/).
111
112We probably have more examples than we need. That said, here's a good way to get started:
113
114- I want the simplest setup going. Use "[vanilla](examples/vanilla)" `ts-loader`
115- 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.
116
117### Faster Builds
118
119As 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*.
120
121You 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).
122
123If 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).
124
125### Yarn Plug’n’Play
126
127`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).
128
129### Babel
130
131`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).
132
133### Parallelising Builds
134
135It'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)
136
137But 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.)
138
139To 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.
140
141If 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).
142
143### Compatibility
144
145* TypeScript: 2.4.1+
146* webpack: 4.x+ (please use `ts-loader` 3.x if you need webpack 2 or 3 support)
147* node: 6.11.5 minimum (aligned with webpack 4)
148
149A 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).
150
151If 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!
152
153### Configuration
154
1551. Create or update `webpack.config.js` like so:
156
157 ```javascript
158 module.exports = {
159 mode: "development",
160 devtool: "inline-source-map",
161 entry: "./app.ts",
162 output: {
163 filename: "bundle.js"
164 },
165 resolve: {
166 // Add `.ts` and `.tsx` as a resolvable extension.
167 extensions: [".ts", ".tsx", ".js"]
168 },
169 module: {
170 rules: [
171 // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
172 { test: /\.tsx?$/, loader: "ts-loader" }
173 ]
174 }
175 };
176 ```
177
1782. 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)
179
180 ```json
181 {
182 "compilerOptions": {
183 "sourceMap": true
184 }
185 }
186 ```
187
188The [tsconfig.json](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html) file controls
189TypeScript-related options so that your IDE, the `tsc` command, and this loader all share the
190same options.
191
192#### `devtool` / sourcemaps
193
194If 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.
195
196First, 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`.
197
198Second, 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:
199
200* `devtool: 'inline-source-map'` - Solid sourcemap support; the best "all-rounder". Works well with karma-webpack (not all strategies do)
201* `devtool: 'cheap-module-eval-source-map'` - Best support for sourcemaps whilst debugging.
202* `devtool: 'source-map'` - Approach that plays well with UglifyJsPlugin; typically you might use this in Production
203
204### Code Splitting and Loading Other Resources
205
206Loading css and other resources is possible but you will need to make sure that
207you have defined the `require` function in a [declaration file](https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html).
208
209```typescript
210declare var require: {
211 <T>(path: string): T;
212 (paths: string[], callback: (...modules: any[]) => void): void;
213 ensure: (
214 paths: string[],
215 callback: (require: <T>(path: string) => T) => void
216 ) => void;
217};
218```
219
220Then you can simply require assets or chunks per the [webpack documentation](https://webpack.js.org/guides/code-splitting/).
221
222```javascript
223require("!style!css!./style.css");
224```
225
226The same basic process is required for code splitting. In this case, you `import` modules you need but you
227don'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.
228
229[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!
230
231### Declarations (.d.ts)
232
233To 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.
234
235### Failing the build on TypeScript compilation error
236
237The 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).
238
239For more background have a read of [this issue](https://github.com/TypeStrong/ts-loader/issues/108).
240
241### `baseUrl` / `paths` module resolution
242
243If 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).
244
245This 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.
246
247```javascript
248const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
249
250module.exports = {
251 ...
252 resolve: {
253 plugins: [new TsconfigPathsPlugin({ configFile: "./path/to/tsconfig.json" })]
254 }
255 ...
256}
257```
258
259### Options
260
261There 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:
262
263```javascript
264module.exports = {
265 ...
266 module: {
267 rules: [
268 {
269 test: /\.tsx?$/,
270 use: [
271 {
272 loader: 'ts-loader',
273 options: {
274 transpileOnly: true
275 }
276 }
277 ]
278 }
279 ]
280 }
281}
282```
283
284### Loader Options
285
286#### transpileOnly
287| Type | Default Value |
288|------|--------------|
289| `boolean` | `false`|
290
291If you want to speed up compilation significantly you can set this flag.
292However, many of the benefits you get from static type checking between
293different dependencies in your application will be lost.
294
295It'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).
296
297If you enable this option, webpack 4 will give you "export not found" warnings any time you re-export a type:
298
299```
300WARNING in ./src/bar.ts
3011:0-34 "export 'IFoo' was not found in './foo'
302 @ ./src/bar.ts
303 @ ./src/index.ts
304```
305
306The 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:
307
308```javascript
309module.exports = {
310 ...
311 stats: {
312 warningsFilter: /export .* was not found in/
313 }
314}
315```
316
317#### happyPackMode
318| Type | Default Value |
319|------|--------------|
320| `boolean` | `false`|
321
322If 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.
323
324It'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:
325
326```javascript
327 new ForkTsCheckerWebpackPlugin({
328 typescript: {
329 diagnosticOptions: {
330 semantic: true,
331 syntactic: true,
332 },
333 },
334 })
335```
336
337This 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).
338
339Also, if you are using `thread-loader` in watch mode, remember to set `poolTimeout: Infinity` so workers don't die.
340
341#### resolveModuleName and resolveTypeReferenceDirective
342
343These 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).
344
345#### getCustomTransformers
346| Type |
347|------|
348| ` (program: Program) => { before?: TransformerFactory<SourceFile>[]; after?: TransformerFactory<SourceFile>[]; } ` |
349
350Provide 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).
351
352You 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))
353
354#### logInfoToStdOut
355| Type | Default Value |
356|------|--------------|
357| `boolean` | `false`|
358
359This is important if you read from stdout or stderr and for proper error handling.
360The default value ensures that you can read from stdout e.g. via pipes or you use webpack -j to generate json output.
361
362#### logLevel
363| Type | Default Value |
364|------|--------------|
365| `string` | `warn` |
366
367Can be `info`, `warn` or `error` which limits the log output to the specified log level.
368Beware of the fact that errors are written to stderr and everything else is written to stderr (or stdout if logInfoToStdOut is true).
369
370#### silent
371| Type | Default Value |
372|------|--------------|
373| `boolean` | `false`|
374
375If `true`, no console.log messages will be emitted. Note that most error
376messages are emitted via webpack which is not affected by this flag.
377
378#### ignoreDiagnostics
379| Type | Default Value |
380|------|--------------|
381| `number[]` | `[]`|
382
383You can squelch certain TypeScript errors by specifying an array of diagnostic
384codes to ignore.
385
386#### reportFiles
387| Type | Default Value |
388|------|--------------|
389| `string[]` | `[]`|
390
391Only report errors on files matching these glob patterns.
392
393```javascript
394 // in webpack.config.js
395 {
396 test: /\.ts$/,
397 loader: 'ts-loader',
398 options: { reportFiles: ['src/**/*.{ts,tsx}', '!src/skip.ts'] }
399 }
400```
401
402This can be useful when certain types definitions have errors that are not fatal to your application.
403
404#### compiler
405| Type | Default Value |
406|------|--------------|
407| `string` | `'typescript'`|
408
409Allows use of TypeScript compilers other than the official one. Should be
410set to the NPM name of the compiler, eg [`ntypescript`](https://github.com/basarat/ntypescript).
411
412#### configFile
413| Type | Default Value |
414|------|--------------|
415| `string` | `'tsconfig.json'`|
416
417Allows you to specify where to find the TypeScript configuration file.
418
419You may provide
420
421* 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.
422* a relative path to the configuration file. It will be resolved relative to the respective `.ts` entry file.
423* an absolute path to the configuration file.
424
425Please 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).
426In this case the `configFile` should point to the `tsconfig.json` and `context` to the project root.
427
428#### colors
429| Type | Default Value |
430|------|--------------|
431| `boolean` | `true`|
432
433If `false`, disables built-in colors in logger messages.
434
435#### errorFormatter
436| Type | Default Value |
437|------|--------------|
438| `(message: ErrorInfo, colors: boolean) => string` | `undefined`|
439
440By default `ts-loader` formats TypeScript compiler output for an error or a warning in the style:
441
442```
443[tsl] ERROR in myFile.ts(3,14)
444 TS4711: you did something very wrong
445```
446
447If 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.)
448
449```javascript
450function customErrorFormatter(error, colors) {
451 const messageColor =
452 error.severity === "warning" ? colors.bold.yellow : colors.bold.red;
453 return (
454 "Does not compute.... " +
455 messageColor(Object.keys(error).map(key => `${key}: ${error[key]}`))
456 );
457}
458```
459
460If the above formatter received an error like this:
461
462```json
463{
464 "code":2307,
465 "severity": "error",
466 "content": "Cannot find module 'components/myComponent2'.",
467 "file":"/.test/errorFormatter/app.ts",
468 "line":2,
469 "character":31
470}
471```
472
473It would produce an error message that said:
474
475```
476Does not compute.... code: 2307,severity: error,content: Cannot find module 'components/myComponent2'.,file: /.test/errorFormatter/app.ts,line: 2,character: 31
477```
478
479And the bit after "Does not compute.... " would be red.
480
481#### compilerOptions
482| Type | Default Value |
483|------|--------------|
484| `object` | `{}`|
485
486Allows overriding TypeScript options. Should be specified in the same format
487as you would do for the `compilerOptions` property in tsconfig.json.
488
489#### instance
490| Type | Default Value |
491|------|--------------|
492| `string` | `TODO`|
493
494Advanced option to force files to go through different instances of the
495TypeScript compiler. Can be used to force segregation between different parts
496of your code.
497
498#### appendTsSuffixTo
499| Type | Default Value |
500|------|--------------|
501| `(RegExp | string)[]` | `[]`|
502
503#### appendTsxSuffixTo
504| Type | Default Value |
505|------|--------------|
506| `(RegExp | string)[]` | `[]`|
507
508A 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.
509If 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.
510
511```js
512// change this:
513{ appendTsSuffixTo: [/\.vue$/] }
514// to:
515{ appendTsSuffixTo: ['\\.vue$'] }
516```
517
518
519This 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.)
520
521Example:
522
523webpack.config.js:
524
525```javascript
526module.exports = {
527 entry: "./index.vue",
528 output: { filename: "bundle.js" },
529 resolve: {
530 extensions: [".ts", ".vue"]
531 },
532 module: {
533 rules: [
534 { test: /\.vue$/, loader: "vue-loader" },
535 {
536 test: /\.ts$/,
537 loader: "ts-loader",
538 options: { appendTsSuffixTo: [/\.vue$/] }
539 }
540 ]
541 }
542};
543```
544
545index.vue
546
547```vue
548<template><p>hello {{msg}}</p></template>
549<script lang="ts">
550export default {
551 data(): Object {
552 return {
553 msg: "world"
554 };
555 }
556};
557</script>
558```
559
560We can handle `.tsx` by quite similar way:
561
562webpack.config.js:
563
564```javascript
565module.exports = {
566 entry: './index.vue',
567 output: { filename: 'bundle.js' },
568 resolve: {
569 extensions: ['.ts', '.tsx', '.vue', '.vuex']
570 },
571 module: {
572 rules: [
573 { test: /\.vue$/, loader: 'vue-loader',
574 options: {
575 loaders: {
576 ts: 'ts-loader',
577 tsx: 'babel-loader!ts-loader',
578 }
579 }
580 },
581 { test: /\.ts$/, loader: 'ts-loader', options: { appendTsSuffixTo: [/TS\.vue$/] } }
582 { test: /\.tsx$/, loader: 'babel-loader!ts-loader', options: { appendTsxSuffixTo: [/TSX\.vue$/] } }
583 ]
584 }
585}
586```
587
588tsconfig.json (set `jsx` option to `preserve` to let babel handle jsx)
589
590```json
591{
592 "compilerOptions": {
593 "jsx": "preserve"
594 }
595}
596```
597
598index.vue
599
600```vue
601<script lang="tsx">
602export default {
603 functional: true,
604 render(h, c) {
605 return (<div>Content</div>);
606 }
607}
608</script>
609```
610
611Or if you want to use only tsx, just use the `appendTsxSuffixTo` option only:
612
613```javascript
614 { test: /\.ts$/, loader: 'ts-loader' }
615 { test: /\.tsx$/, loader: 'babel-loader!ts-loader', options: { appendTsxSuffixTo: [/\.vue$/] } }
616```
617
618#### onlyCompileBundledFiles
619| Type | Default Value |
620|------|--------------|
621| `boolean` | `false`|
622
623The default behavior of `ts-loader` is to act as a drop-in replacement for the `tsc` command,
624so it respects the `include`, `files`, and `exclude` options in your `tsconfig.json`, loading
625any files specified by those options. The `onlyCompileBundledFiles` option modifies this behavior,
626loading only those files that are actually bundled by webpack, as well as any `.d.ts` files included
627by the `tsconfig.json` settings. `.d.ts` files are still included because they may be needed for
628compilation without being explicitly imported, and therefore not picked up by webpack.
629
630#### allowTsInNodeModules
631| Type | Default Value |
632|------|--------------|
633| `boolean` | `false`|
634
635By default, `ts-loader` will not compile `.ts` files in `node_modules`.
636You should not need to recompile `.ts` files there, but if you really want to, use this option.
637Note that this option acts as a *whitelist* - any modules you desire to import must be included in
638the `"files"` or `"include"` block of your project's `tsconfig.json`.
639
640See: [https://github.com/Microsoft/TypeScript/issues/12358](https://github.com/Microsoft/TypeScript/issues/12358)
641
642```javascript
643 // in webpack.config.js
644 {
645 test: /\.ts$/,
646 loader: 'ts-loader',
647 options: { allowTsInNodeModules: true }
648 }
649```
650
651And in your `tsconfig.json`:
652
653```json
654 {
655 "include": [
656 "node_modules/whitelisted_module.ts"
657 ],
658 "files": [
659 "node_modules/my_module/whitelisted_file.ts"
660 ]
661 }
662```
663
664#### context
665| Type | Default Value |
666|------|--------------|
667| `string` | `undefined`|
668
669If set, will parse the TypeScript configuration file with given **absolute path** as base path.
670Per default the directory of the configuration file is used as base path. Relative paths in the configuration
671file are resolved with respect to the base path when parsed. Option `context` allows to set option
672`configFile` to a path other than the project root (e.g. a NPM package), while the base path for `ts-loader`
673can remain the project root.
674
675Keep in mind that **not** having a `tsconfig.json` in your project root can cause different behaviour between `ts-loader` and `tsc`.
676When 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
677referenced in option `configFile`. For more information please [read the PR](https://github.com/TypeStrong/ts-loader/pull/681) that
678is the base and [read the PR](https://github.com/TypeStrong/ts-loader/pull/688) that contributed this option.
679
680webpack:
681
682```javascript
683{
684 loader: require.resolve('ts-loader'),
685 options: {
686 context: __dirname,
687 configFile: require.resolve('ts-config-react-app')
688 }
689}
690```
691
692Extending `tsconfig.json`:
693
694```json
695{ "extends": "./node_modules/ts-config-react-app/index" }
696```
697
698Note that changes in the extending file while not be respected by `ts-loader`. Its purpose is to satisfy the code editor.
699
700#### experimentalFileCaching
701| Type | Default Value |
702|------|--------------|
703| `boolean` | `true`|
704
705By 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).
706In some cases it may produce performance degradation.
707
708This flag enables caching for some FS-functions like `fileExists`, `realpath` and `directoryExists` for TypeScript compiler. Note that caches are cleared between compilations.
709
710#### projectReferences
711| Type | Default Value |
712|------|--------------|
713| `boolean` | `false`|
714
715ts-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.
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