fork-ts-checker-webpack-plugin

repository·main·Indexed 24 days ago

https://github.com/typestrong/fork-ts-checker-webpack-plugin

A Webpack plugin that runs TypeScript type checking and linting in a separate process to speed up build times. It supports modern TypeScript features such as project references and incremental mode, and provides integration options for babel-loader, ts-loader, and Visual Studio Code.

Tokens
4.7K
Snippets
8
Records
18
Agent score
84%

What's inside fork-ts-checker-webpack-plugin

  1. Filter issues with the issue option

    main

    The issue option allows you to include or exclude specific issues based on their properties (severity, code, or file) or via a predicate function.

    An Issue object contains:

    • severity: 'error' | 'warning'
    • code: string
    • file: string (supports glob matching)

    You can provide an IssueMatch (partial object), an IssuePredicate (function), or an array of both to the include or exclude keys.

    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)[];
  2. Understand module resolution in fork-ts-checker-webpack-plugin

    main

    The plugin uses TypeScript's module resolution, not Webpack's. This is done for performance reasons to avoid waiting for Webpack to compile files.

    Because of this, you must ensure your tsconfig.json is configured correctly for your module resolution needs. If you encounter resolution issues, you can debug them using the TypeScript command: tsc --traceResolution.

  3. Configure fork-ts-checker-webpack-plugin via cosmiconfig

    main

    The plugin supports external configuration using cosmiconfig. You can define your configuration in one of the following locations:

    1. The "fork-ts-checker" field in your package.json.
    2. A .fork-ts-checkerrc file in JSON or YAML format.
    3. A fork-ts-checker.config.js file that exports a JavaScript object.

    Note: Options passed directly to the plugin constructor in your Webpack configuration will overwrite options found in cosmiconfig files using deep merging.

  4. Configure ForkTsCheckerWebpackPlugin with babel-loader

    main

    When using babel-loader instead of ts-loader, you must enable syntactic diagnostics in the plugin configuration to ensure that TypeScript syntax errors are caught. This is because babel-loader only handles transpilation and does not perform type checking itself.

    To enable these diagnostics, set semantic and syntactic to true within the typescript.diagnosticOptions object.

    new ForkTsCheckerWebpackPlugin({
      typescript: {
        diagnosticOptions: {
          semantic: true,
          syntactic: true,
        },
      },
    })
  5. Install fork-ts-checker-webpack-plugin

    main

    Install the plugin as a development dependency using your preferred package manager.

    Requirements:

    • Node.js >=14.0.0+
    • Webpack ^5.11.0
    • TypeScript ^3.6.0

    Version Compatibility Notes:

    # with npm
    npm install --save-dev fork-ts-checker-webpack-plugin
    
    # with yarn
    yarn add --dev fork-ts-checker-webpack-plugin
    
    # with pnpm
    pnpm add -D fork-ts-checker-webpack-plugin
  6. Profile TypeScript type resolution

    main

    If you are using TypeScript 4.3.0 or newer, you can profile long type checks using the generateTrace compiler option:

    1. Set "generateTrace": "{folderName}" in your tsconfig.json under compilerOptions.
    2. Locate the resulting folder. If using build mode, it contains legend.json. Otherwise, it contains trace.json and types.json files.
    3. Open chrome://tracing or edge://tracing in your browser and load the trace.json file.
    4. Expand Process 1 in the sidebar to inspect payloads.
    5. To map type IDs from the tracing output to actual data, open types.json in an editor and use the ID to find the corresponding type information.
  7. Display webpack errors in Visual Studio Code Problems tab

    main

    To see type-checking errors from fork-ts-checker-webpack-plugin directly in the Visual Studio Code Problems tab, you must configure a .vscode/tasks.json file. This configuration uses a problem matcher to parse the webpack output and map errors to the correct files and lines.

    This specific implementation relies on the TypeScript + Webpack Problem Matchers extension by @eamodio to correctly interpret the error output.

  8. Include and exclude specific issues

    main

    Use the issue property in the plugin configuration to filter which errors and warnings are reported. For example, you can include only issues from a specific directory and exclude test files using glob patterns.

    module.exports = {
      // ...the webpack configuration
      plugins: [
        new ForkTsCheckerWebpackPlugin({
          issue: {
            include: [
              { file: '**/src/**/*' }
            ],
            exclude: [
              { file: '**/*.spec.ts' }
            ]
          }
        })
      ]
    };
  9. Configure fork-ts-checker-webpack-plugin with ts-loader

    main

    To use the plugin with ts-loader, add ForkTsCheckerWebpackPlugin to your Webpack plugins array. Ensure your context is set (usually to __dirname) so the plugin can automatically find your tsconfig.json.

    If you are using ts-loader version < 9.3.0, you should enable the transpileOnly: true option in the ts-loader configuration to avoid double type-checking, as this plugin handles type checking in a separate process.

    // 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/,
      },
    };
  10. Access plugin hooks via getCompilerHooks

    main

    The plugin provides custom webpack hooks that allow you to tap into the issue-checking lifecycle. To access these hooks, use the ForkTsCheckerWebpackPlugin.getCompilerHooks(compiler) static method, passing in your webpack compiler instance. This returns an object containing tapable hooks.

    Available hooks:

    • start (AsyncSeriesWaterfallHook): Starts issue checking. You can modify the list of changed/removed files or delay the service start.
    • waiting (SyncHook): Triggered while waiting for issue checking.
    • canceled (SyncHook): Triggered when issue checking is canceled.
    • error (SyncHook): Triggered when an error occurs during issue checking.
    • issues (SyncWaterfallHook): Triggered when issues are received. You can modify the list of received issues (e.g., to filter them).
    // ./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()
      ]
    };
  11. Configure changelog generation settings

    main

    The changelog.config.js file defines how changelogs are generated, including allowed commit types, message length constraints, and the structure of the changelog questions. You can customize the list of valid types, their descriptions, and which sections they appear in.

    module.exports = {
      list: ['feat', 'fix', 'refactor', 'perf', 'test', 'chore', 'docs'],
      maxMessageLength: 64,
      minMessageLength: 3,
      questions: ['type', 'subject', 'body', 'breaking', 'issues'],
      types: {
        feat: {
          description: 'A new feature',
          value: 'feat',
          section: 'Features',
        },
        fix: {
          description: 'A bug fix',
          value: 'fix',
          section: 'Bug Fixes',
        },
        // ... other types
      },
    };