-
Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathtransform-replace-console-calls.js
More file actions
82 lines (78 loc) · 2.51 KB
/
transform-replace-console-calls.js
File metadata and controls
82 lines (78 loc) · 2.51 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const helperModuleImports = require('@babel/helper-module-imports');
module.exports = function replaceConsoleCalls(babel) {
let consoleErrors = new WeakMap();
function getConsoleError(path, file) {
if (!consoleErrors.has(file)) {
consoleErrors.set(
file,
helperModuleImports.addNamed(
path,
'error',
'shared/consoleWithStackDev',
{nameHint: 'consoleError'}
)
);
}
return babel.types.cloneDeep(consoleErrors.get(file));
}
let consoleWarns = new WeakMap();
function getConsoleWarn(path, file) {
if (!consoleWarns.has(file)) {
consoleWarns.set(
file,
helperModuleImports.addNamed(
path,
'warn',
'shared/consoleWithStackDev',
{nameHint: 'consoleWarn'}
)
);
}
return babel.types.cloneDeep(consoleWarns.get(file));
}
return {
visitor: {
CallExpression: function(path, pass) {
if (path.node.callee.type !== 'MemberExpression') {
return;
}
if (path.node.callee.property.type !== 'Identifier') {
// Don't process calls like console['error'](...)
// because they serve as an escape hatch.
return;
}
if (path.get('callee').matchesPattern('console.error')) {
if (this.opts.shouldError) {
throw path.buildCodeFrameError(
"This module has no access to the React object, so it can't " +
'use console.error() with automatically appended stack. ' +
"As a workaround, you can use console['error'] which won't " +
'be transformed.'
);
}
const id = getConsoleError(path, pass.file);
path.node.callee = id;
}
if (path.get('callee').matchesPattern('console.warn')) {
if (this.opts.shouldError) {
throw path.buildCodeFrameError(
"This module has no access to the React object, so it can't " +
'use console.warn() with automatically appended stack. ' +
"As a workaround, you can use console['warn'] which won't " +
'be transformed.'
);
}
const id = getConsoleWarn(path, pass.file);
path.node.callee = id;
}
},
},
};
};