1
- const fs = require ( 'fs' )
1
+ import type { Node , PluginObj , PluginPass } from '@babel/core'
2
2
import * as helperModuleImports from '@babel/helper-module-imports'
3
3
import * as fs from 'node:fs'
4
+ import * as path from 'node:path'
5
+
6
+ type Babel = typeof import ( '@babel/core' )
7
+
8
+ /**
9
+ * Represents the options for the {@linkcode mangleErrorsPlugin}.
10
+ *
11
+ * @internal
12
+ */
13
+ export interface MangleErrorsPluginOptions {
14
+ /**
15
+ * Whether to minify the error messages or not.
16
+ * If `true`, the error messages will be replaced with an index
17
+ * that maps object lookup.
18
+ */
19
+ minify : boolean
20
+ }
4
21
5
22
/**
6
23
* Converts an AST type into a JavaScript string so that it can be added to the error message lookup.
7
24
*
8
25
* Adapted from React (https://github.com/facebook/react/blob/master/scripts/shared/evalToString.js) with some
9
26
* adjustments.
10
27
*/
11
- const evalToString = ( ast ) => {
28
+ const evalToString = (
29
+ ast : Node | { type : 'Literal' ; value : string } ,
30
+ ) : string => {
12
31
switch ( ast . type ) {
13
32
case 'StringLiteral' :
14
33
case 'Literal' : // ESLint
@@ -55,7 +74,10 @@ const evalToString = (ast) => {
55
74
* throw new Error(process.env.NODE_ENV === 'production' ? 0 : "This is my error message.");
56
75
* throw new Error(process.env.NODE_ENV === 'production' ? 1 : "This is a second error message.");
57
76
*/
58
- export const mangleErrorsPlugin = ( babel ) => {
77
+ export const mangleErrorsPlugin = (
78
+ babel : Babel ,
79
+ options : MangleErrorsPluginOptions ,
80
+ ) : PluginObj < PluginPass & MangleErrorsPluginOptions > => {
59
81
const t = babel . types
60
82
// When the plugin starts up, we'll load in the existing file. This allows us to continually add to it so that the
61
83
// indexes do not change between builds.
@@ -65,7 +87,7 @@ export const mangleErrorsPlugin = (babel) => {
65
87
if ( fs . existsSync ( errorsPath ) ) {
66
88
errorsFiles = fs . readFileSync ( errorsPath ) . toString ( )
67
89
}
68
- let errors = Object . values ( JSON . parse ( errorsFiles || '{}' ) )
90
+ const errors = Object . values ( JSON . parse ( errorsFiles || '{}' ) )
69
91
// This variable allows us to skip writing back to the file if the errors array hasn't changed
70
92
let changeInArray = false
71
93
0 commit comments