Load modules according to tsconfig paths in webpack.
npx @tessl/cli install tessl/npm-tsconfig-paths-webpack-plugin@4.2.00
# TsconfigPathsPlugin
1
2
TsconfigPathsPlugin is a webpack resolver plugin that enables automatic module resolution based on TypeScript path mapping configuration from tsconfig.json. It eliminates the need for manual webpack alias configuration by reading the paths section from tsconfig.json and creating corresponding aliases automatically.
3
4
## Package Information
5
6
- **Package Name**: tsconfig-paths-webpack-plugin
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install --save-dev tsconfig-paths-webpack-plugin`
10
11
## Core Imports
12
13
```typescript
14
import TsconfigPathsPlugin from "tsconfig-paths-webpack-plugin";
15
```
16
17
Named import:
18
19
```typescript
20
import { TsconfigPathsPlugin } from "tsconfig-paths-webpack-plugin";
21
```
22
23
For CommonJS:
24
25
```javascript
26
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
27
```
28
29
## Basic Usage
30
31
```javascript
32
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
33
34
module.exports = {
35
resolve: {
36
plugins: [new TsconfigPathsPlugin()]
37
}
38
};
39
```
40
41
With configuration options:
42
43
```javascript
44
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
45
46
module.exports = {
47
resolve: {
48
plugins: [
49
new TsconfigPathsPlugin({
50
configFile: "./tsconfig.json",
51
extensions: [".ts", ".tsx", ".js"],
52
mainFields: ["browser", "main"],
53
logLevel: "warn"
54
})
55
]
56
}
57
};
58
```
59
60
## Architecture
61
62
TsconfigPathsPlugin integrates with webpack's resolve system through the ResolvePluginInstance interface. It:
63
64
- **Parses tsconfig.json**: Reads TypeScript configuration files to extract path mappings
65
- **Creates Path Matchers**: Uses the tsconfig-paths library to create async path matching functions
66
- **Hooks into Webpack Resolver**: Implements webpack's resolver plugin interface to intercept module resolution
67
- **Supports References**: Handles TypeScript project references for monorepo scenarios
68
- **Legacy Compatibility**: Supports both modern webpack (4+) and legacy webpack (<4) plugin systems
69
70
## Capabilities
71
72
### TsconfigPathsPlugin Class
73
74
Main webpack resolver plugin that resolves modules using tsconfig.json paths configuration.
75
76
```typescript { .api }
77
/**
78
* Webpack resolver plugin for TypeScript path mapping
79
*/
80
class TsconfigPathsPlugin implements ResolvePluginInstance {
81
/**
82
* Creates a new TsconfigPathsPlugin instance
83
* @param rawOptions - Configuration options (defaults to empty object)
84
*/
85
constructor(rawOptions: Partial<Options> = {});
86
87
/**
88
* Webpack plugin interface method - called by webpack resolver
89
* @param resolver - The webpack resolver instance
90
*/
91
apply(resolver: Resolver): void;
92
}
93
```
94
95
**Usage Examples:**
96
97
```typescript
98
// Basic usage with defaults
99
const plugin = new TsconfigPathsPlugin();
100
101
// With TypeScript import
102
import TsconfigPathsPlugin from "tsconfig-paths-webpack-plugin";
103
const plugin = new TsconfigPathsPlugin({
104
configFile: "./src/tsconfig.json",
105
extensions: [".ts", ".tsx", ".js", ".jsx"]
106
});
107
108
// For monorepos with project references
109
const plugin = new TsconfigPathsPlugin({
110
references: ["./packages/core/tsconfig.json", "./packages/utils/tsconfig.json"]
111
});
112
```
113
114
### Configuration Options
115
116
All configuration options for customizing plugin behavior.
117
118
```typescript { .api }
119
interface Options {
120
/** Path to tsconfig.json file - can be filename, relative path, or absolute path */
121
readonly configFile: string;
122
/** File extensions to try during module resolution */
123
readonly extensions: ReadonlyArray<string>;
124
/** Override baseUrl from tsconfig.json */
125
readonly baseUrl: string | undefined;
126
/** Suppress console log messages */
127
readonly silent: boolean;
128
/** Logging level for plugin messages */
129
readonly logLevel: LogLevel;
130
/** Output info logs to stdout instead of stderr */
131
readonly logInfoToStdOut: boolean;
132
/** Context directory for resolving relative paths */
133
readonly context: string | undefined;
134
/** Enable colored terminal output */
135
readonly colors: boolean;
136
/** Package.json fields to consider when resolving packages */
137
readonly mainFields: (string | string[])[];
138
/** TypeScript project references for monorepo support */
139
readonly references: string[] | undefined;
140
}
141
142
type LogLevel = "INFO" | "WARN" | "ERROR";
143
```
144
145
**Default Values:**
146
147
- `configFile`: `"tsconfig.json"`
148
- `extensions`: `[".ts", ".tsx"]`
149
- `baseUrl`: `undefined` (uses tsconfig.json value)
150
- `silent`: `false`
151
- `logLevel`: `"WARN"`
152
- `logInfoToStdOut`: `false`
153
- `context`: `undefined` (uses current working directory)
154
- `colors`: `true`
155
- `mainFields`: `["main"]`
156
- `references`: `undefined`
157
158
**Usage Examples:**
159
160
```typescript
161
// Custom tsconfig location
162
new TsconfigPathsPlugin({
163
configFile: "./src/tsconfig.build.json"
164
});
165
166
// Support additional file extensions
167
new TsconfigPathsPlugin({
168
extensions: [".ts", ".tsx", ".js", ".jsx", ".vue"]
169
});
170
171
// Override baseUrl for build scenarios
172
new TsconfigPathsPlugin({
173
baseUrl: "./dist"
174
});
175
176
// Silent mode for production builds
177
new TsconfigPathsPlugin({
178
silent: true
179
});
180
181
// Debug mode with detailed logging
182
new TsconfigPathsPlugin({
183
logLevel: "INFO",
184
logInfoToStdOut: true
185
});
186
187
// Browser-compatible package resolution
188
new TsconfigPathsPlugin({
189
mainFields: ["browser", "module", "main"]
190
});
191
192
// Monorepo with project references
193
new TsconfigPathsPlugin({
194
references: [
195
"./packages/core/tsconfig.json",
196
"./packages/shared/tsconfig.json"
197
]
198
});
199
```
200
201
### Logger Interface
202
203
Internal logging system used by the plugin.
204
205
```typescript { .api }
206
interface Logger {
207
/** General logging output */
208
log: LoggerFunc;
209
/** Info level messages */
210
logInfo: LoggerFunc;
211
/** Warning level messages */
212
logWarning: LoggerFunc;
213
/** Error level messages */
214
logError: LoggerFunc;
215
}
216
217
type LoggerFunc = (message: string) => void;
218
```
219
220
## Types
221
222
```typescript { .api }
223
/**
224
* Webpack resolver instance interface (from webpack)
225
*/
226
interface Resolver {
227
readonly fileSystem: FileSystem;
228
getHook?(hook: string): AsyncSeriesBailHook<[ResolveRequest, ResolveContext], null | ResolveRequest>;
229
doResolve: Function;
230
}
231
232
/**
233
* Webpack resolve plugin interface
234
*/
235
interface ResolvePluginInstance {
236
apply(resolver: Resolver): void;
237
}
238
239
/**
240
* File system interface used by webpack resolver
241
*/
242
interface FileSystem {
243
readFile: Function;
244
stat: Function;
245
}
246
```
247
248
## Error Handling
249
250
The plugin handles several error conditions:
251
252
- **Missing tsconfig.json**: Logs error and disables path resolution
253
- **Invalid tsconfig.json**: Logs parsing errors with file location
254
- **Resolver placement errors**: Warns if plugin is not in resolve.plugins array
255
- **File system errors**: Gracefully handles missing files during resolution
256
- **Path resolution failures**: Falls back to webpack's default resolution
257
258
Common error messages:
259
260
```
261
"Failed to load tsconfig.json: [error details]"
262
"No file system found on resolver. Please make sure you've placed the plugin in the correct part of the configuration."
263
"Found no resolver, not applying tsconfig-paths-webpack-plugin"
264
```