Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

fork-ts-checker-webpack-plugin

TypeStrong46.5mMIT9.0.2TypeScript support: included

Runs typescript type checker and linter on separate process.

webpack, plugin, typescript, typecheck, ts-loader, webpack, fork, fast

readme

SWUbanner

Fork TS Checker Webpack Plugin

Webpack plugin that runs TypeScript type checker on a separate process.

npm version build status downloads commitizen friendly code style: prettier semantic-release

Features

Installation

This plugin requires Node.js >=14.0.0+, Webpack ^5.11.0, TypeScript ^3.6.0

  • If you depend on TypeScript 2.1 - 2.6.2, please use version 4 of the plugin.
  • If you depend on Webpack 4, TypeScript 2.7 - 3.5.3 or ESLint feature, please use version 6 of the plugin.
  • If you depend on Node.js 12, please use version 8 of the plugin.
  • If you need Vue.js support, please use version 6 of ths plugin
# with npm
npm install --save-dev fork-ts-checker-webpack-plugin

# with yarn
yarn add --dev fork-ts-checker-webpack-plugin

The minimal webpack config (with ts-loader)

// webpack.config.js
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

module.exports = {
  context: __dirname, // to automatically find tsconfig.json
  entry: './src/index.ts',
  resolve: {
    extensions: [".ts", ".tsx", ".js"],
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        // add transpileOnly option if you use ts-loader < 9.3.0 
        // options: {
        //   transpileOnly: true
        // }
      }
    ]
  },
  plugins: [new ForkTsCheckerWebpackPlugin()],
  watchOptions: {
    // for some systems, watching many files can result in a lot of CPU or memory usage
    // https://webpack.js.org/configuration/watch/#watchoptionsignored
    // don't use this pattern, if you have a monorepo with linked packages
    ignored: /node_modules/,
  },
};

Examples how to configure it with babel-loader, ts-loader and Visual Studio Code are in the examples directory.

Modules resolution

It's very important to be aware that this plugin uses TypeScript's, not webpack's modules resolution. It means that you have to setup tsconfig.json correctly.

It's because of the performance - with TypeScript's module resolution we don't have to wait for webpack to compile files.

To debug TypeScript's modules resolution, you can use tsc --traceResolution command.

Options

This plugin uses cosmiconfig. This means that besides the plugin constructor, you can place your configuration in the:

  • "fork-ts-checker" field in the package.json
  • .fork-ts-checkerrc file in JSON or YAML format
  • fork-ts-checker.config.js file exporting a JS object

Options passed to the plugin constructor will overwrite options from the cosmiconfig (using deepmerge).

Name Type Default value Description
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.
typescript object {} See TypeScript options.
issue object {} See Issues options.
formatter string or object or function codeframe Available formatters are basic, codeframe and a custom function. To configure codeframe formatter, pass: { type: 'codeframe', options: { <coderame options> } }. To use absolute file path, pass: { type: 'codeframe', pathType: 'absolute' }.
logger { log: function, error: function } or webpack-infrastructure console Console-like object to print issues in async mode.
devServer boolean true If set to false, errors will not be reported to Webpack Dev Server.

TypeScript options

Options for the TypeScript checker (typescript option object).

Name Type Default value Description
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.
configFile string 'tsconfig.json' Path to the tsconfig.json file (path relative to the compiler.options.context or absolute path)
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.
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. 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.
build boolean false The equivalent of the --build flag for the tsc command.
mode 'readonly' or 'write-dts' or 'write-tsbuildinfo' or 'write-references' build === true ? 'write-tsbuildinfo' ? 'readonly' Use readonly if you don't want to write anything on the disk, write-dts to write only .d.ts files, write-tsbuildinfo to write only .tsbuildinfo files, write-references to write both .js and .d.ts files of project references (last 2 modes requires build: true).
diagnosticOptions object { syntactic: false, semantic: true, declaration: false, global: false } Settings to select which diagnostics do we want to perform.
profile boolean false Measures and prints timings related to the TypeScript performance.
typescriptPath string require.resolve('typescript') If supplied this is a custom path where TypeScript can be found.

Issues options

Options for the issues filtering (issue option object). I could write some plain text explanation of these options but I think code will explain it better:

interface Issue {
  severity: 'error' | 'warning';
  code: string;
  file?: string;
}

type IssueMatch = Partial<Issue>; // file field supports glob matching
type IssuePredicate = (issue: Issue) => boolean;
type IssueFilter = IssueMatch | IssuePredicate | (IssueMatch | IssuePredicate)[];
Name Type Default value Description
include IssueFilter undefined If object, defines issue properties that should be matched. If function, acts as a predicate where issue is an argument.
exclude IssueFilter undefined Same as include but issues that match this predicate will be excluded.
<summary>Expand example</summary>

Include issues from the src directory, exclude issues from .spec.ts files:

module.exports = {
  // ...the webpack configuration
  plugins: [
    new ForkTsCheckerWebpackPlugin({
      issue: {
        include: [
          { file: '**/src/**/*' }
        ],
        exclude: [
          { file: '**/*.spec.ts' }
        ]
      }
    })
  ]
};

Plugin hooks

This plugin provides some custom webpack hooks:

Hook key Type Params Description
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.
waiting SyncHook compilation Waiting for the issues checking.
canceled SyncHook compilation Issues checking for the compilation has been canceled.
error SyncHook compilation An error occurred during issues checking.
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.

To access plugin hooks and tap into the event, we need to use the getCompilerHooks static method. When we call this method with a webpack compiler instance, it returns the object with tapable hooks where you can pass in your callbacks.

// ./src/webpack/MyWebpackPlugin.js
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

class MyWebpackPlugin {
  apply(compiler) {
    const hooks = ForkTsCheckerWebpackPlugin.getCompilerHooks(compiler);

    // log some message on waiting
    hooks.waiting.tap('MyPlugin', () => {
      console.log('waiting for issues');
    });
    // don't show warnings
    hooks.issues.tap('MyPlugin', (issues) =>
      issues.filter((issue) => issue.severity === 'error')
    );
  }
}

module.exports = MyWebpackPlugin;

// webpack.config.js
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const MyWebpackPlugin = require('./src/webpack/MyWebpackPlugin');

module.exports = {
  /* ... */
  plugins: [
    new ForkTsCheckerWebpackPlugin(),
    new MyWebpackPlugin()
  ]
};

Profiling types resolution

When using TypeScript 4.3.0 or newer you can profile long type checks by setting "generateTrace" compiler option. This is an instruction from microsoft/TypeScript#40063:

  1. Set "generateTrace": "{folderName}" in your tsconfig.json (under compilerOptions)
  2. Look in the resulting folder. If you used build mode, there will be a legend.json telling you what went where. Otherwise, there will be trace.json file and types.json files.
  3. Navigate to edge://tracing or chrome://tracing and load trace.json
  4. Expand Process 1 with the little triangle in the left sidebar
  5. Click on different blocks to see their payloads in the bottom pane
  6. Open types.json in an editor
  7. When you see a type ID in the tracing output, go-to-line {id} to find data about that type

Enabling incremental mode

You must both set "incremental": true in your tsconfig.json (under compilerOptions) and also specify mode: 'write-references' in ForkTsCheckerWebpackPlugin settings.

Credits

This plugin was created in Realytics in 2017. Thank you for supporting Open Source.

License

MIT License

changelog

⚠️ Next versions are available only on the GitHub Releases page ⚠️

1.3.0-beta.1 (2019-04-30)

Bug Fixes

  • tests: fix linter tests that were doing nothing (d078278)
  • tests: linter tests - useTypescriptIncrementalApi usage (e0020d6)
  • tests: rework vue integration tests (5ad2568)

Features

  • apiincrementalchecker: improve generation of diagnostics (ae80e5f), closes #257

1.2.0 (2019-04-22)

Bug Fixes

  • semantic-release update CHANGELOG.md on the git repo (8ad58af)

Features

  • add semantic-release integration (5fe0653)

1.2.0-beta.4 (2019-04-23)

Bug Fixes

  • tests: fix linter tests that were doing nothing (d078278)
  • tests: linter tests - useTypescriptIncrementalApi usage (e0020d6)

Features

  • apiincrementalchecker: improve generation of diagnostics (ae80e5f), closes #257

1.2.0-beta.3 (2019-04-22)

Bug Fixes

  • tests: rework vue integration tests (5ad2568)

1.2.0-beta.2 (2019-04-22)

Bug Fixes

  • semantic-release update CHANGELOG.md on the git repo (8ad58af)

1.2.0-beta.1 (2019-04-22)

Features

  • add semantic-release integration (5fe0653)

v1.1.1

v1.1.0

v1.0.4

v1.0.3

v1.0.2

v1.0.1

v1.0.0

This is the first major version of fork-ts-checker-webpack-plugin. A long time coming :-)

There are actually no breaking changes that we're aware of; users of 0.x fork-ts-checker-webpack-plugin should be be able to upgrade without any drama. Users of TypeScript 3+ may notice a performance improvement as by default the plugin now uses the incremental watch API in TypeScript. Should this prove problematic you can opt out of using it by supplying useTypescriptIncrementalApi: false.

We are aware of an issue with Vue and the incremental API. We hope it will be fixed soon - a generous member of the community is taking a look. In the meantime, we will not default to using the incremental watch API when in Vue mode.

The plugin supports webpack 2, 3, 4 and 5 alpha and TypeScript 2.1+ alongside tslint 4+.

See also: https://johnnyreilly.com/2019/03/06/fork-ts-checker-webpack-plugin-v1

v1.0.0-alpha.10

v1.0.0-alpha.9

v1.0.0-alpha.8

v1.0.0-alpha.7

v1.0.0-alpha.6

v1.0.0-alpha.5

v1.0.0-alpha.4

v1.0.0-alpha.3

v1.0.0-alpha.2

v1.0.0-alpha.1

v1.0.0-alpha.0

Breaking Changes

Version 1.x additionally supports webpack 5 alongside webpack 4, whose hooks are now tapped differently:

-  compiler.hooks.forkTsCheckerDone.tap(...args)
+  const forkTsCheckerHooks = ForkTsCheckerWebpackPlugin.getCompilerHooks(compiler)
+  forkTsCheckerHooks.done.tap(...args)

v1.0.0-alpha.0 drops support for node 6.

v0.5.2

v0.5.1

0.5.0

  • Removed unused dependency resolve.
  • Replace lodash usage with native calls.
  • ** Breaking Changes**:
    • Removed all getters from NormalizedMessage, use direct property access instead.
  • Internal:
    • Test against ts-loader v5
    • Enable all strict type checks
    • Update dev dependencies

v0.4.15

v0.4.14

v0.4.13

v0.4.12

v0.4.11

v0.4.10

v0.4.9

v0.4.8

v0.4.7

v0.4.6

v0.4.5

v0.4.4

v0.4.3

  • Fix "File system lag can cause Invalid source file errors to slip through" (#127)

v0.4.2

  • Format messages when async is false

v0.4.1

  • Fix webpack 4 hooks bug

v0.4.0

  • Support webpack 4

v0.3.0

  • Add vue support

v0.2.10

  • Fix #80 "Cannot read property 'getLineAndCharacterOfPosition' of undefined"
  • Fix #76 "TypeError: Cannot read property '0' of undefined"

v0.2.9

  • Make errors formatting closer to ts-loader style
  • Handle tslint exclude option

v0.2.8

  • Add checkSyntacticErrors option
  • Fix process.env pass to the child process
  • Add fork-ts-checker-service-before-start hook

v0.2.7

  • Fix service is not killed when webpack watch is done

v0.2.6

  • Add diagnostics/lints formatters - formatter and formatterOptions option

v0.2.5

  • Add async option - more information in README.md

v0.2.4

  • Fix ESLint: "fork-ts-checker-webpack-plugin" is not published. issue

v0.2.3

  • Add support for webpack 3 as peerDependency

v0.2.2

  • Force isolatedModule: false in checker compiler for better performance

v0.2.1

  • Fix for tslint: true option issue

v0.2.0

  • tsconfig.json and tslint.json path are not printed anymore.
  • watch option is not used on 'build' mode
  • Handle case with no options object (new ForkTsCheckerWebpacPlugin())
  • Basic integration tests (along units)
  • Breaking changes:
    • tslint is not enabled by default - you have to set tslint: true or tslint: './path/to/tslint.json' to enable it.
    • blockEmit option is removed - it choose automatically - blocks always on 'build' mode, never on 'watch' mode.

v0.1.5

  • Disable tslint if module is not installed and no tslint path is passed
  • Improve README.md

v0.1.4

  • Fix send to closed channel case
  • Fix removed files case
  • Add fork-ts-checker-service-start-error hook

v0.1.3

  • Fix "Cannot read property 'mtime' of undefined on OSX"

v0.1.2

  • Workers mode works correctly (fixed typo)

v0.1.1

  • Support memory limit in multi-process mode
  • Handle already closed channel case on sending ipc message

v0.1.0

  • Initial release - not production ready.