Repository navigation
Expand file tree
/
Copy pathwebpack.js
More file actions
59 lines (53 loc) · 2.43 KB
/
Copy pathwebpack.js
File metadata and controls
59 lines (53 loc) · 2.43 KB
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
const ModuleAppenderDependency = require('./lib/module-appender')
const OptionsParser = require('./lib/options-parser')
const { detectReactComponents, generateDisplayNameCode } = require('./lib/component-detector')
const VALID_FILE_SUFFIXES_REGEX = /\.(js|jsx|ts|tsx)$/
// Normally React component names are minified during compilation. This plugin
// makes these component names available in production bundles by hooking into
// Webpack's compilation process, traversing the AST looking for React component
// definitions, and updating the emitted source code to populate the
// displayName property. This is the property that, when populated, is used by the React Dev
// Tools extension to determine the name of a component.
//
// For more information on the AST format and API, see:
// https://github.com/estree/estree
// https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API
// noinspection JSUnusedGlobalSymbols
class ReactDisplayNamePlugin {
constructor(options) {
this.options = new OptionsParser().parse(options)
}
apply(compiler) {
compiler.hooks.compilation.tap(
"ReactDisplayNamePlugin",
(compilation) => {
compilation.dependencyTemplates.set(
ModuleAppenderDependency,
new ModuleAppenderDependency.Template()
)
}
)
compiler.hooks.normalModuleFactory.tap('ReactDisplayNamePlugin', factory => {
factory.hooks.parser.for('javascript/auto').tap('ReactDisplayNamePlugin', parser => {
parser.hooks.program.tap("ReactDisplayNamePlugin", ast => {
// Ignore dependency files
if (parser.state.current.resource == null
|| !VALID_FILE_SUFFIXES_REGEX.test(parser.state.current.resource.toLowerCase())
|| (this.options.include.length && this.options.include.every(match => !match(parser.state.current.resource)))
|| (this.options.exclude.length && this.options.exclude.some(match => match(parser.state.current.resource)))) {
return
}
// Use shared component detection logic
detectReactComponents(ast, (node) => {
const componentName = node.id.name
const code = generateDisplayNameCode(componentName)
const dep = new ModuleAppenderDependency(code, node.range)
dep.loc = node.loc
parser.state.module.addDependency(dep)
})
})
})
})
}
}
module.exports = ReactDisplayNamePlugin