source: frontend/node_modules/fork-ts-checker-webpack-plugin/README.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 13 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 21.1 KB
Line 
1<div align="center">
2
3<h1>Fork TS Checker Webpack Plugin</h1>
4<p>Webpack plugin that runs TypeScript type checker on a separate process.</p>
5
6[![npm version](https://img.shields.io/npm/v/fork-ts-checker-webpack-plugin.svg)](https://www.npmjs.com/package/fork-ts-checker-webpack-plugin)
7[![build status](https://github.com/TypeStrong/fork-ts-checker-webpack-plugin/workflows/CI/CD/badge.svg?branch=main&event=push)](https://github.com/TypeStrong/fork-ts-checker-webpack-plugin/actions?query=branch%3Amain+event%3Apush)
8[![downloads](http://img.shields.io/npm/dm/fork-ts-checker-webpack-plugin.svg)](https://npmjs.org/package/fork-ts-checker-webpack-plugin)
9[![commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
10[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
11[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
12
13</div>
14
15## Features
16
17 * Speeds up [TypeScript](https://github.com/Microsoft/TypeScript) type checking and [ESLint](https://eslint.org/) linting (by moving each to a separate process) 🏎
18 * Supports modern TypeScript features like [project references](https://www.typescriptlang.org/docs/handbook/project-references.html) and [incremental mode](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#faster-subsequent-builds-with-the---incremental-flag) ✨
19 * Supports [Vue Single File Component](https://vuejs.org/v2/guide/single-file-components.html) ✅ 
20 * Displays nice error messages with the [code frame](https://babeljs.io/docs/en/next/babel-code-frame.html) formatter 🌈
21
22## Installation
23
24This plugin requires minimum **Node.js 10**, **Webpack 4**, **TypeScript 2.7** and optionally **ESLint 6**
25
26* If you depend on **Webpack 2**, **Webpack 3**, or **TSLint 4**, please use [version 3](https://github.com/TypeStrong/fork-ts-checker-webpack-plugin/tree/v3.1.1) of the plugin.
27* If you depend on **TypeScript >= 2.1** and **< 2.7** or you can't update to **Node 10**, please use [version 4](https://github.com/TypeStrong/fork-ts-checker-webpack-plugin/tree/v4.1.4) of the plugin.
28```sh
29# with npm
30npm install --save-dev fork-ts-checker-webpack-plugin
31
32# with yarn
33yarn add --dev fork-ts-checker-webpack-plugin
34```
35
36The minimal webpack config (with [ts-loader](https://github.com/TypeStrong/ts-loader))
37
38```js
39// webpack.config.js
40const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
41
42module.exports = {
43 context: __dirname, // to automatically find tsconfig.json
44 entry: './src/index.ts',
45 resolve: {
46 extensions: [".ts", ".tsx", ".js"],
47 },
48 module: {
49 rules: [
50 {
51 test: /\.tsx?$/,
52 loader: 'ts-loader',
53 exclude: /node_modules/,
54 options: {
55 // disable type checker - we will use it in fork plugin
56 transpileOnly: true
57 }
58 }
59 ]
60 },
61 plugins: [new ForkTsCheckerWebpackPlugin()]
62};
63```
64
65> Examples how to configure it with [babel-loader](https://github.com/babel/babel-loader), [ts-loader](https://github.com/TypeStrong/ts-loader),
66> [eslint](https://github.com/eslint/eslint) and [Visual Studio Code](https://code.visualstudio.com/) are in the
67> [**examples**](./examples) directory.
68
69## Modules resolution
70
71It's very important to be aware that **this plugin uses [TypeScript](https://github.com/Microsoft/TypeScript)'s, not
72[webpack](https://github.com/webpack/webpack)'s modules resolution**. It means that you have to setup `tsconfig.json` correctly.
73
74> It's because of the performance - with TypeScript's module resolution we don't have to wait for webpack to compile files.
75>
76> To debug TypeScript's modules resolution, you can use `tsc --traceResolution` command.
77
78## ESLint
79
80If you'd like to use ESLint with the plugin, ensure you have the relevant dependencies installed:
81
82```sh
83# with npm
84npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
85
86# with yarn
87yarn add --dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
88```
89
90Then set up ESLint in the plugin. This is the minimal configuration:
91```js
92// webpack.config.js
93const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
94
95module.exports = {
96 // ...the webpack configuration
97 plugins: [
98 new ForkTsCheckerWebpackPlugin({
99 eslint: {
100 files: './src/**/*.{ts,tsx,js,jsx}' // required - same as command `eslint ./src/**/*.{ts,tsx,js,jsx} --ext .ts,.tsx,.js,.jsx`
101 }
102 })
103 ]
104};
105```
106
107You should also have an ESLint configuration file in your root project directory.
108Here is a sample `.eslintrc.js` configuration for a TypeScript project:
109
110```js
111module.exports = {
112 parser: '@typescript-eslint/parser',
113 parserOptions: {
114 ecmaVersion: 2018,
115 sourceType: 'module',
116 },
117 extends: [
118 'plugin:@typescript-eslint/recommended'
119 ],
120 rules: {
121 // place to specify ESLint rules - can be used to overwrite rules specified from the extended configs
122 // e.g. "@typescript-eslint/explicit-function-return-type": "off",
123 }
124};
125```
126
127There's a [good explanation on setting up TypeScript ESLint support by Robert Cooper](https://dev.to/robertcoopercode/using-eslint-and-prettier-in-a-typescript-project-53jb).
128
129## Options
130
131This plugin uses [`cosmiconfig`](https://github.com/davidtheclark/cosmiconfig). This means that besides the plugin constructor,
132you can place your configuration in the:
133 * `"fork-ts-checker"` field in the `package.json`
134 * `.fork-ts-checkerrc` file in JSON or YAML format
135 * `fork-ts-checker.config.js` file exporting a JS object
136
137Options passed to the plugin constructor will overwrite options from the cosmiconfig (using [deepmerge](https://github.com/TehShrike/deepmerge)).
138
139| Name | Type | Default value | Description |
140| ----------------- | ---------------------------------- | ------------------------------------------------------------------ | ----------- |
141| `async` | `boolean` | `compiler.options.mode === 'development'` | If `true`, reports issues **after** webpack's compilation is done. Thanks to that it doesn't block the compilation. Used only in the `watch` mode. |
142| `typescript` | `object` or `boolean` | `true` | If a `boolean`, it enables/disables TypeScript checker. If an `object`, see [TypeScript options](#typescript-options). |
143| `eslint` | `object` | `undefined` | If `undefined`, it disables ESLint linter. If an `object`, see [ESLint options](#eslint-options). |
144| `issue` | `object` | `{}` | See [Issues options](#issues-options). |
145| `formatter` | `string` or `object` or `function` | `codeframe` | Available formatters are `basic`, `codeframe` and a custom `function`. To [configure](https://babeljs.io/docs/en/babel-code-frame#options) `codeframe` formatter, pass object: `{ type: 'codeframe', options: { <coderame options> } }`. |
146| `logger` | `object` | `{ infrastructure: 'silent', issues: 'console', devServer: true }` | Available loggers are `silent`, `console`, and `webpack-infrastructure`. Infrastructure logger prints additional information, issue logger prints `issues` in the `async` mode. If `devServer` is set to `false`, errors will not be reported to Webpack Dev Server. |
147
148### TypeScript options
149
150Options for the TypeScript checker (`typescript` option object).
151
152| Name | Type | Default value | Description |
153| -------------------- | --------- | -------------------------------------------------------------------------------------------------------------- | ----------- |
154| `enabled` | `boolean` | `true` | If `true`, it enables TypeScript checker. |
155| `memoryLimit` | `number` | `2048` | Memory limit for the checker process in MB. If the process exits with the allocation failed error, try to increase this number. |
156| `configFile` | `string` | `'tsconfig.json'` | Path to the `tsconfig.json` file (path relative to the `compiler.options.context` or absolute path) |
157| `configOverwrite` | `object` | `{ compilerOptions: { skipLibCheck: true, sourceMap: false, inlineSourceMap: false, declarationMap: false } }` | This configuration will overwrite configuration from the `tsconfig.json` file. Supported fields are: `extends`, `compilerOptions`, `include`, `exclude`, `files`, and `references`. |
158| `context` | `string` | `dirname(configuration.configFile)` | The base path for finding files specified in the `tsconfig.json`. Same as the `context` option from the [ts-loader](https://github.com/TypeStrong/ts-loader#context). Useful if you want to keep your `tsconfig.json` in an external package. Keep in mind that **not** having a `tsconfig.json` in your project root can cause different behaviour between `fork-ts-checker-webpack-plugin` and `tsc`. When 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 referenced in option `configFile`. |
159| `build` | `boolean` | `false` | The equivalent of the `--build` flag for the `tsc` command. |
160| `mode` | `'readonly'` or `'write-tsbuildinfo'` or `'write-dts'` or `'write-references'` | `'write-tsbuildinfo'` | If you use the `babel-loader`, it's recommended to use `write-references` mode to improve initial compilation time. If you use `ts-loader`, it's recommended to use `write-tsbuildinfo` mode to not overwrite files emitted by the `ts-loader`. If you use `ts-loader` with `transpileOnly` flag set to `true`, use `'write-dts` to emit the type definition files. |
161| `diagnosticOptions` | `object` | `{ syntactic: false, semantic: true, declaration: false, global: false }` | Settings to select which diagnostics do we want to perform. |
162| `extensions` | `object` | `{}` | See [TypeScript extensions options](#typescript-extensions-options). |
163| `profile` | `boolean` | `false` | Measures and prints timings related to the TypeScript performance. |
164| `typescriptPath` | `string` | `require.resolve('typescript')` | If supplied this is a custom path where TypeScript can be found. |
165
166#### TypeScript extensions options
167
168Options for the TypeScript checker extensions (`typescript.extensions` option object).
169
170| Name | Type | Default value | Description |
171| -------------------- | --------------------- | ------------------------- | ----------- |
172| `vue` | `object` or `boolean` | `false` | If `true`, it enables Vue [Single File Component](https://vuejs.org/v2/guide/single-file-components.html) support. |
173| `vue.enabled` | `boolean` | `false` | Same as the `vue` option |
174| `vue.compiler` | `string` | `'vue-template-compiler'` | The package name of the compiler that will be used to parse `.vue` files. You can use `'nativescript-vue-template-compiler'` if you use [nativescript-vue](https://github.com/nativescript-vue/nativescript-vue) |
175
176### ESLint options
177
178Options for the ESLint linter (`eslint` option object).
179
180| Name | Type | Default value | Description |
181| -------------------- | ---------------------- | ------------------------- | ----------- |
182| `enabled` | `boolean` | `false` | If `true`, it enables ESLint linter. If you set the `files` option, it will be `true` by default. |
183| `files` | `string` or `string[]` | This value is required | One or more [glob patterns](https://en.wikipedia.org/wiki/Glob_(programming)) to the files that should be linted. Works the same as the `eslint` command. |
184| `memoryLimit` | `number` | `2048` | Memory limit for the linter process in MB. If the process exits with the allocation failed error, try to increase this number. |
185| `options` | `object` | `{}` | [Options](https://eslint.org/docs/developer-guide/nodejs-api#cliengine) that can be used to initialize ESLint. |
186
187### Issues options
188
189Options for the issues filtering (`issue` option object).
190I could write some plain text explanation of these options but I think code will explain it better:
191
192```typescript
193interface Issue {
194 origin: 'typescript' | 'eslint';
195 severity: 'error' | 'warning';
196 code: string;
197 file?: string;
198}
199
200type IssueMatch = Partial<Issue>; // file field supports glob matching
201type IssuePredicate = (issue: Issue) => boolean;
202type IssueFilter = IssueMatch | IssuePredicate | (IssueMatch | IssuePredicate)[];
203```
204
205| Name | Type | Default value | Description |
206| --------- | ------------- | ------------- | ----------- |
207| `include` | `IssueFilter` | `undefined` | If `object`, defines issue properties that should be [matched](./src/issue/IssueMatch.ts). If `function`, acts as a predicate where `issue` is an argument. |
208| `exclude` | `IssueFilter` | `undefined` | Same as `include` but issues that match this predicate will be excluded. |
209
210<details>
211<summary>Expand example</summary>
212
213Include issues from the `src` directory, exclude eslint issues from `.spec.ts` files:
214
215```js
216module.exports = {
217 // ...the webpack configuration
218 plugins: [
219 new ForkTsCheckerWebpackPlugin({
220 issue: {
221 include: [
222 { file: '**/src/**/*' }
223 ],
224 exclude: [
225 { origin: 'eslint', file: '**/*.spec.ts' }
226 ]
227 }
228 })
229 ]
230};
231```
232
233</details>
234
235## Vue.js
236
237⚠️ There are additional **constraints** regarding Vue.js Single File Component support: ⚠️
238 * It requires **TypeScript >= 3.8.0** (it's a limitation of the `transpileOnly` mode from `ts-loader`)
239 * It doesn't work with the `build` mode (project references)
240
241To enable Vue.js support, follow these steps:
242
243<details>
244<summary>Expand Vue.js set up instruction</summary>
245
2461. Ensure you have all required packages installed:
247```sh
248# with npm
249npm install --save vue vue-class-component
250npm install --save-dev vue-loader ts-loader css-loader vue-template-compiler
251
252# with yarn
253yarn add vue vue-class-component
254yarn add --dev vue-loader ts-loader css-loader vue-template-compiler
255```
256
2572. Add `tsconfig.json` configuration:
258```json
259{
260 "compilerOptions": {
261 "experimentalDecorators": true,
262 "jsx": "preserve",
263 "target": "ES5",
264 "lib": ["ES6", "DOM"],
265 "baseUrl": ".",
266 "paths": {
267 "@/*": ["src/*"],
268 "~/*": ["src/*"]
269 },
270 "sourceMap": true,
271 "importsNotUsedAsValues": "preserve"
272 },
273 "include": [
274 "src/**/*.ts",
275 "src/**/*.vue"
276 ],
277 "exclude": [
278 "node_modules"
279 ]
280}
281```
282
2833. Add `webpack.config.js` configuration:
284```js
285const path = require('path');
286const VueLoaderPlugin = require('vue-loader/lib/plugin');
287const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
288
289module.exports = {
290 entry: './src/index.ts',
291 output: {
292 filename: 'index.js',
293 path: path.resolve(__dirname, 'dist'),
294 },
295 module: {
296 rules: [
297 {
298 test: /\.vue$/,
299 loader: 'vue-loader'
300 },
301 {
302 test: /\.ts$/,
303 loader: 'ts-loader',
304 exclude: /node_modules/,
305 options: {
306 appendTsSuffixTo: [/\.vue$/],
307 transpileOnly: true
308 }
309 },
310 {
311 test: /\.css$/,
312 loader: 'css-loader'
313 },
314 ],
315 },
316 resolve: {
317 extensions: ['.ts', '.js', '.vue', '.json'],
318 alias: {
319 '@': path.resolve(__dirname, './src'),
320 '~': path.resolve(__dirname, './src'),
321 }
322 },
323 plugins: [
324 new VueLoaderPlugin(),
325 new ForkTsCheckerWebpackPlugin({
326 typescript: {
327 extensions: {
328 vue: true
329 }
330 }
331 })
332 ]
333};
334```
335
3364. Add `src/types/vue.d.ts` file to shim `.vue` modules:
337```typescript
338declare module "*.vue" {
339 import Vue from "vue";
340 export default Vue;
341}
342```
343
3445. If you are working in VSCode, you can get the [Vetur](https://marketplace.visualstudio.com/items?itemName=octref.vetur) extension to complete the developer workflow.
345
346</details>
347
348## Plugin hooks
349
350This plugin provides some custom webpack hooks:
351
352| Hook key | Type | Params | Description |
353| ---------- | -------------------------- | --------------------- | ----------- |
354| `start` | `AsyncSeriesWaterfallHook` | `change, compilation` | Starts issues checking for a compilation. It's an async waterfall hook, so you can modify the list of changed and removed files or delay the start of the service. |
355| `waiting` | `SyncHook` | `compilation` | Waiting for the issues checking. |
356| `canceled` | `SyncHook` | `compilation` | Issues checking for the compilation has been canceled. |
357| `error` | `SyncHook` | `compilation` | An error occurred during issues checking. |
358| `issues` | `SyncWaterfallHook` | `issues, compilation` | Issues have been received and will be reported. It's a waterfall hook, so you can modify the list of received issues. |
359
360To access plugin hooks and tap into the event, we need to use the `getCompilerHooks` static method.
361When we call this method with a [webpack compiler instance](https://webpack.js.org/api/node/), it returns the object with
362[tapable](https://github.com/webpack/tapable) hooks where you can pass in your callbacks.
363
364```js
365// ./src/webpack/MyWebpackPlugin.js
366const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
367
368class MyWebpackPlugin {
369 apply(compiler) {
370 const hooks = ForkTsCheckerWebpackPlugin.getCompilerHooks(compiler);
371
372 // log some message on waiting
373 hooks.waiting.tap('MyPlugin', () => {
374 console.log('waiting for issues');
375 });
376 // don't show warnings
377 hooks.issues.tap('MyPlugin', (issues) =>
378 issues.filter((issue) => issue.severity === 'error')
379 );
380 }
381}
382
383module.exports = MyWebpackPlugin;
384
385// webpack.config.js
386const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
387const MyWebpackPlugin = require('./src/webpack/MyWebpackPlugin');
388
389module.exports = {
390 /* ... */
391 plugins: [
392 new ForkTsCheckerWebpackPlugin(),
393 new MyWebpackPlugin()
394 ]
395};
396```
397
398## Typings
399
400To use the plugin typings, you have to install `@types/webpack`. It's not included by default to not collide with your
401existing typings (`@types/webpack` imports `@types/node`). [It's an old TypeScript issue](https://github.com/microsoft/TypeScript/issues/18588),
402the alternative is to set `skipLibCheck: true` in the `compilerOptions` 😉
403```sh
404# with npm
405npm install --save-dev @types/webpack
406
407# with yarn
408yarn add --dev @types/webpack
409```
410
411## Profiling types resolution
412
413Starting from TypeScript 4.1.0, you can profile long type checks by
414setting "generateTrace" compiler option. This is an instruction from [microsoft/TypeScript#40063](https://github.com/microsoft/TypeScript/pull/40063):
415
4161. Set "generateTrace": "{folderName}" in your `tsconfig.json`
4172. Look in the resulting folder. If you used build mode, there will be a `legend.json` telling you what went where.
418 Otherwise, there will be `trace.json` file and `types.json` files.
4193. Navigate to [edge://tracing](edge://tracing) or [chrome://tracing](chrome://tracing) and load `trace.json`
4204. Expand Process 1 with the little triangle in the left sidebar
4215. Click on different blocks to see their payloads in the bottom pane
4226. Open `types.json` in an editor
4237. When you see a type ID in the tracing output, go-to-line {id} to find data about that type
424
425
426## Related projects
427
428 * [`ts-loader`](https://github.com/TypeStrong/ts-loader) - TypeScript loader for webpack.
429 * [`babel-loader`](https://github.com/babel/babel-loader) - Alternative TypeScript loader for webpack.
430 * [`fork-ts-checker-notifier-webpack-plugin`](https://github.com/johnnyreilly/fork-ts-checker-notifier-webpack-plugin) - Notifies about build status using system notifications (similar to the [webpack-notifier](https://github.com/Turbo87/webpack-notifier)).
431
432## Credits
433
434This plugin was created in [Realytics](https://www.realytics.io/) in 2017. Thank you for supporting Open Source.
435
436## License
437
438MIT License
Note: See TracBrowser for help on using the repository browser.