-
Notifications
You must be signed in to change notification settings - Fork 28
/
plugin.ts
262 lines (222 loc) · 6.73 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
/* eslint-disable no-param-reassign, no-underscore-dangle */
import path from "path";
import createDebug from "debug";
import * as webpack from "webpack";
import ts from "typescript";
import * as docGen from "react-docgen-typescript";
import { matcher } from "micromatch";
import findCacheDir from "find-cache-dir";
import flatCache from "flat-cache";
import crypto from "crypto";
import { generateDocgenCodeBlock } from "./generateDocgenCodeBlock";
const debugExclude = createDebug("docgen:exclude");
const debugInclude = createDebug("docgen:include");
const debugDocs = createDebug("docgen:docs");
const cacheId = "ts-docgen";
const cacheDir = findCacheDir({ name: cacheId });
const cache = flatCache.load(cacheId, cacheDir);
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;
}
interface LoaderOptions {
/**
* Specify the docgen collection name to use. All docgen information will
* be collected into this global object. Set to null to disable.
*
* @default STORYBOOK_REACT_CLASSES
* @see https://github.com/gongreg/react-storybook-addon-docgen
**/
docgenCollectionName?: string | null;
/**
* Automatically set the component's display name. If you want to set display
* names yourself or are using another plugin to do this, you should disable
* this option.
*
* ```
* class MyComponent extends React.Component {
* ...
* }
*
* MyComponent.displayName = "MyComponent";
* ```
*
* @default true
*/
setDisplayName?: boolean;
/**
* Specify the name of the property for docgen info prop type.
*
* @default "type"
*/
typePropName?: string;
}
export type PluginOptions = docGen.ParserOptions &
LoaderOptions &
TypescriptOptions & {
/** Glob patterns to ignore */
exclude?: string[];
/** Glob patterns to include. defaults to ts|tsx */
include?: string[];
};
interface Module {
userRequest: string;
request: string;
built?: boolean;
rawRequest?: string;
external?: boolean;
_source: {
_value: string;
};
}
/** Run the docgen parser and inject the result into the output */
function processModule(
parser: docGen.FileParser,
webpackModule: Module,
tsProgram: ts.Program,
loaderOptions: Required<LoaderOptions>
) {
if (!webpackModule) {
return;
}
const hash = crypto
.createHash("sha1")
.update(webpackModule._source._value)
.digest("hex");
const cached = cache.getKey(hash);
if (cached) {
debugInclude(`Got cached docgen for "${webpackModule.request}"`);
webpackModule._source._value = cached;
return;
}
const componentDocs = parser.parseWithProgramProvider(
webpackModule.userRequest,
() => tsProgram
);
if (!componentDocs.length) {
return;
}
const docs = generateDocgenCodeBlock({
filename: webpackModule.userRequest,
source: webpackModule.userRequest,
componentDocs,
...loaderOptions,
}).substring(webpackModule.userRequest.length);
debugDocs(docs);
let sourceWithDocs = webpackModule._source._value;
sourceWithDocs += `\n${docs}\n`;
webpackModule._source._value = sourceWithDocs;
cache.setKey(hash, sourceWithDocs);
}
/** 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));
return (filename: string) =>
Boolean(filename && matchers.find((match) => match(filename)));
};
/** Inject typescript docgen information into modules at the end of a build */
export default class DocgenPlugin {
private name = "React Docgen Typescript Plugin";
private options: PluginOptions;
constructor(options: PluginOptions = {}) {
this.options = options;
}
apply(compiler: webpack.Compiler): void {
const {
tsconfigPath = "./tsconfig.json",
docgenCollectionName = "STORYBOOK_REACT_CLASSES",
setDisplayName = true,
typePropName = "type",
compilerOptions: userCompilerOptions,
exclude = [],
include = ["**/**.tsx"],
...docgenOptions
} = this.options;
const isExcluded = matchGlob(exclude);
const isIncluded = matchGlob(include);
let compilerOptions = {
jsx: ts.JsxEmit.React,
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.Latest,
};
if (userCompilerOptions) {
compilerOptions = {
...compilerOptions,
...userCompilerOptions,
};
} else {
const { options } = getTSConfigFile(tsconfigPath);
compilerOptions = { ...compilerOptions, ...options };
}
const parser = docGen.withCompilerOptions(compilerOptions, docgenOptions);
compiler.hooks.make.tap(this.name, (compilation) => {
compilation.hooks.seal.tap(this.name, () => {
const modulesToProcess: Module[] = [];
compilation.modules.forEach((module: Module) => {
if (!module.built) {
debugExclude(`Ignoring un-built module: ${module.userRequest}`);
return;
}
if (module.external) {
debugExclude(`Ignoring external module: ${module.userRequest}`);
return;
}
if (!module.rawRequest) {
debugExclude(
`Ignoring module without "rawRequest": ${module.userRequest}`
);
return;
}
if (isExcluded(module.userRequest)) {
debugExclude(
`Module not matched in "exclude": ${module.userRequest}`
);
return;
}
if (!isIncluded(module.userRequest)) {
debugExclude(
`Module not matched in "include": ${module.userRequest}`
);
return;
}
debugInclude(module.userRequest);
modulesToProcess.push(module);
});
const tsProgram = ts.createProgram(
modulesToProcess.map((v) => v.userRequest),
compilerOptions
);
modulesToProcess.forEach((m) =>
processModule(parser, m, tsProgram, {
docgenCollectionName,
setDisplayName,
typePropName,
})
);
cache.save();
});
});
}
}
export type DocgenPluginType = typeof DocgenPlugin;