-
Notifications
You must be signed in to change notification settings - Fork 28
/
plugin.ts
298 lines (260 loc) · 8.63 KB
/
plugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import path from "path";
import createDebug from "debug";
import ts from "typescript";
import * as docGen from "react-docgen-typescript";
import { matcher } from "micromatch";
import * as webpack from "webpack";
import findCacheDir from "find-cache-dir";
import flatCache from "flat-cache";
import crypto from "crypto";
import { LoaderOptions } from "./types";
import {
generateDocgenCodeBlock,
GeneratorOptions,
} from "./generateDocgenCodeBlock";
const debugExclude = createDebug("docgen:exclude");
const debugInclude = createDebug("docgen:include");
interface TypescriptOptions {
/**
* Specify the location of the tsconfig.json to use. Can not be used with
* compilerOptions.
**/
tsconfigPath?: string;
/** Specify TypeScript compiler options. Can not be used with tsconfigPath. */
compilerOptions?: ts.CompilerOptions;
}
export type PluginOptions = docGen.ParserOptions &
LoaderOptions &
TypescriptOptions & {
/** Glob patterns to ignore */
exclude?: string[];
/** Glob patterns to include. defaults to ts|tsx */
include?: string[];
};
/** Get the contents of the tsconfig in the system */
function getTSConfigFile(tsconfigPath: string): ts.ParsedCommandLine {
try {
const basePath = path.dirname(tsconfigPath);
const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
return ts.parseJsonConfigFileContent(
configFile.config,
ts.sys,
basePath,
{},
tsconfigPath
);
} catch (error) {
return {} as ts.ParsedCommandLine;
}
}
/** Create a glob matching function. */
const matchGlob = (globs?: string[]) => {
const matchers = (globs || []).map((g) => matcher(g, { dot: true }));
return (filename: string) =>
Boolean(filename && matchers.find((match) => match(filename)));
};
// The cache is used only with webpack 4 for now as webpack 5 comes with caching of its own
const cacheId = "ts-docgen";
const cacheDir = findCacheDir({ name: cacheId });
const cache = flatCache.load(cacheId, cacheDir);
/** Run the docgen parser and inject the result into the output */
/** This is used for webpack 4 or earlier */
function processModule(
parser: docGen.FileParser,
webpackModule: webpack.Module,
tsProgram: ts.Program,
loaderOptions: Required<LoaderOptions>
) {
if (!webpackModule) {
return;
}
const hash = crypto
.createHash("sha1")
// eslint-disable-next-line
// @ts-ignore
// eslint-disable-next-line
.update(webpackModule._source._value)
.digest("hex");
const cached = cache.getKey(hash);
if (cached) {
// eslint-disable-next-line
// @ts-ignore
// eslint-disable-next-line
debugInclude(`Got cached docgen for "${webpackModule.request}"`);
// eslint-disable-next-line
// @ts-ignore
// eslint-disable-next-line
webpackModule._source._value = cached;
return;
}
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
const { userRequest } = webpackModule;
const componentDocs = parser.parseWithProgramProvider(
userRequest,
() => tsProgram
);
if (!componentDocs.length) {
return;
}
const docs = generateDocgenCodeBlock({
filename: userRequest,
source: userRequest,
componentDocs,
...loaderOptions,
}).substring(userRequest.length);
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
// eslint-disable-next-line
let sourceWithDocs = webpackModule._source._value;
sourceWithDocs += `\n${docs}\n`;
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
// eslint-disable-next-line
webpackModule._source._value = sourceWithDocs;
}
/** Inject typescript docgen information into modules at the end of a build */
export default class DocgenPlugin implements webpack.WebpackPluginInstance {
private name = "React Docgen Typescript Plugin";
private options: PluginOptions;
constructor(options: PluginOptions = {}) {
this.options = options;
}
apply(compiler: webpack.Compiler): void {
const pluginName = "DocGenPlugin";
const {
docgenOptions,
compilerOptions,
generateOptions,
} = this.getOptions();
const docGenParser = docGen.withCompilerOptions(
compilerOptions,
docgenOptions
);
const { exclude = [], include = ["**/**.tsx"] } = this.options;
const isExcluded = matchGlob(exclude);
const isIncluded = matchGlob(include);
// Property compiler.version is set only starting from webpack 5
const webpackVersion = compiler.webpack?.version || "";
const isWebpack5 = parseInt(webpackVersion.split(".")[0], 10) >= 5;
compiler.hooks.compilation.tap(
pluginName,
(compilation: webpack.Compilation) => {
if (isWebpack5) {
// Since this file is needed only for webpack 5, load it only then
// to simplify the implementation of the file.
//
// eslint-disable-next-line
const { DocGenDependency } = require("./dependency");
compilation.dependencyTemplates.set(
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
DocGenDependency,
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
new DocGenDependency.Template()
);
}
compilation.hooks.seal.tap(pluginName, () => {
const modulesToProcess: [string, webpack.Module][] = [];
// 1. Aggregate modules to process
compilation.modules.forEach((module: webpack.Module) => {
if (!module.nameForCondition) {
return;
}
const nameForCondition = module.nameForCondition() || "";
if (isExcluded(nameForCondition)) {
debugExclude(
`Module not matched in "exclude": ${nameForCondition}`
);
return;
}
if (!isIncluded(nameForCondition)) {
debugExclude(
`Module not matched in "include": ${nameForCondition}`
);
return;
}
modulesToProcess.push([nameForCondition, module]);
});
// 2. Create a ts program with the modules
const tsProgram = ts.createProgram(
modulesToProcess.map(([name]) => name),
compilerOptions
);
// 3. Process and parse each module and add the type information
// as a dependency
modulesToProcess.forEach(([name, module]) => {
if (isWebpack5) {
// Since this file is needed only for webpack 5, load it only then
// to simplify the implementation of the file.
//
// eslint-disable-next-line
const { DocGenDependency } = require("./dependency");
module.addDependency(
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
new DocGenDependency(
generateDocgenCodeBlock({
filename: name,
source: name,
componentDocs: docGenParser.parseWithProgramProvider(
name,
() => tsProgram
),
...generateOptions,
}).substring(name.length)
)
);
} else {
// Assume webpack 4 or earlier
processModule(docGenParser, module, tsProgram, generateOptions);
}
});
});
}
);
}
getOptions(): {
docgenOptions: docGen.ParserOptions;
generateOptions: {
docgenCollectionName: GeneratorOptions["docgenCollectionName"];
setDisplayName: GeneratorOptions["setDisplayName"];
typePropName: GeneratorOptions["typePropName"];
};
compilerOptions: ts.CompilerOptions;
} {
const {
tsconfigPath = "./tsconfig.json",
compilerOptions: userCompilerOptions,
docgenCollectionName,
setDisplayName,
typePropName,
...docgenOptions
} = this.options;
let compilerOptions = {
jsx: ts.JsxEmit.React,
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.Latest,
};
if (userCompilerOptions) {
compilerOptions = {
...compilerOptions,
...userCompilerOptions,
};
} else {
const { options: tsOptions } = getTSConfigFile(tsconfigPath);
compilerOptions = { ...compilerOptions, ...tsOptions };
}
return {
docgenOptions,
generateOptions: {
docgenCollectionName: docgenCollectionName || "STORYBOOK_REACT_CLASSES",
setDisplayName: setDisplayName || true,
typePropName: typePropName || "type",
},
compilerOptions,
};
}
}
export type DocgenPluginType = typeof DocgenPlugin;