fork-ts-checker-webpack-plugin
Webpack plugin that runs typescript type checker on a separate process.
Top Related Projects
TypeScript loader for webpack
Awesome TypeScript loader for webpack
Quick Overview
Fork TS Checker Webpack Plugin is a Webpack plugin that runs TypeScript type checker on a separate process. This allows for faster compilation by offloading type checking from the main Webpack process, improving overall build performance while maintaining type safety.
Pros
- Improves build performance by running type checking in a separate process
- Supports both TypeScript and ESLint
- Integrates seamlessly with Webpack's compilation process
- Provides detailed error reporting and formatting options
Cons
- May require additional configuration for complex projects
- Can potentially increase memory usage due to running a separate process
- Might not be necessary for smaller projects with quick build times
- Learning curve for users new to Webpack plugins
Code Examples
- Basic usage with Webpack configuration:
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = {
// ... other webpack config
plugins: [
new ForkTsCheckerWebpackPlugin()
]
};
- Advanced configuration with ESLint:
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = {
// ... other webpack config
plugins: [
new ForkTsCheckerWebpackPlugin({
eslint: {
files: './src/**/*.{ts,tsx,js,jsx}'
}
})
]
};
- Custom TypeScript configuration:
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = {
// ... other webpack config
plugins: [
new ForkTsCheckerWebpackPlugin({
typescript: {
configFile: './tsconfig.prod.json'
}
})
]
};
Getting Started
-
Install the plugin:
npm install --save-dev fork-ts-checker-webpack-plugin
-
Add the plugin to your Webpack configuration:
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); module.exports = { // ... other webpack config plugins: [ new ForkTsCheckerWebpackPlugin() ] };
-
Run your Webpack build as usual. The plugin will now handle type checking in a separate process.
Competitor Comparisons
TypeScript loader for webpack
Pros of ts-loader
- Simpler setup and configuration
- Integrated type checking during compilation
- Works well for smaller projects with fewer TypeScript files
Cons of ts-loader
- Can slow down build times, especially for larger projects
- Blocks webpack compilation until TypeScript checking is complete
- May not fully utilize multi-core processors for type checking
Code Comparison
ts-loader configuration:
module.exports = {
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
};
fork-ts-checker-webpack-plugin configuration:
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = {
plugins: [new ForkTsCheckerWebpackPlugin()],
};
The main difference is that ts-loader is configured as a module rule, while fork-ts-checker-webpack-plugin is added as a plugin. fork-ts-checker-webpack-plugin requires additional setup to handle transpilation, often used in combination with babel-loader or ts-loader in transpile-only mode.
fork-ts-checker-webpack-plugin offers better performance for larger projects by running type checking in a separate process, allowing for faster incremental builds and better utilization of multi-core processors. However, it requires a more complex setup and may introduce a slight delay in error reporting compared to ts-loader.
Awesome TypeScript loader for webpack
Pros of awesome-typescript-loader
- Integrates TypeScript compilation directly into the Webpack build process
- Supports incremental compilation, potentially faster for subsequent builds
- Can generate declaration files (.d.ts) during the build process
Cons of awesome-typescript-loader
- No longer actively maintained, with the last update in 2019
- May have compatibility issues with newer versions of TypeScript and Webpack
- Lacks some advanced features like project references support
Code Comparison
awesome-typescript-loader configuration:
module.exports = {
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'awesome-typescript-loader'
}
]
}
}
fork-ts-checker-webpack-plugin configuration:
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = {
plugins: [new ForkTsCheckerWebpackPlugin()]
}
fork-ts-checker-webpack-plugin runs type checking in a separate process, allowing for faster builds and more flexibility. It's actively maintained and supports the latest TypeScript features. However, it requires a separate TypeScript loader (like ts-loader) for transpilation.
awesome-typescript-loader combines transpilation and type checking, which can be simpler to set up but may lead to slower build times for large projects. Its lack of recent updates may pose compatibility issues with newer tooling versions.
For modern TypeScript projects, fork-ts-checker-webpack-plugin is generally recommended due to its active development and performance benefits.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Fork TS Checker Webpack Plugin
Webpack plugin that runs TypeScript type checker on a separate process.
Features
- Speeds up TypeScript type checking (by moving it to a separate process) ð
- Supports modern TypeScript features like project references and incremental mode â¨
- Displays nice error messages with the code frame formatter ð
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
# with pnpm
pnpm add -D 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 thepackage.json
.fork-ts-checkerrc
file in JSON or YAML formatfork-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. |
Expand example
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:
- Set "generateTrace": "{folderName}" in your
tsconfig.json
(undercompilerOptions
) - Look in the resulting folder. If you used build mode, there will be a
legend.json
telling you what went where. Otherwise, there will betrace.json
file andtypes.json
files. - Navigate to edge://tracing or chrome://tracing and load
trace.json
- Expand Process 1 with the little triangle in the left sidebar
- Click on different blocks to see their payloads in the bottom pane
- Open
types.json
in an editor - 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.
Related projects
ts-loader
- TypeScript loader for webpack.babel-loader
- Alternative TypeScript loader for webpack.fork-ts-checker-notifier-webpack-plugin
- Notifies about build status using system notifications (similar to the webpack-notifier).
Credits
This plugin was created in Realytics in 2017. Thank you for supporting Open Source.
License
MIT License
Top Related Projects
TypeScript loader for webpack
Awesome TypeScript loader for webpack
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot