|
| 1 | +const fs = require('fs') |
| 2 | +const helperModuleImports = require('@babel/helper-module-imports') |
| 3 | + |
| 4 | +/** |
| 5 | + * Converts an AST type into a javascript string so that it can be added to the error message lookup. |
| 6 | + * |
| 7 | + * Adapted from React (https://github.com/facebook/react/blob/master/scripts/shared/evalToString.js) with some |
| 8 | + * adjustments |
| 9 | + */ |
| 10 | +const evalToString = ast => { |
| 11 | + switch (ast.type) { |
| 12 | + case 'StringLiteral': |
| 13 | + case 'Literal': // ESLint |
| 14 | + return ast.value |
| 15 | + case 'BinaryExpression': // `+` |
| 16 | + if (ast.operator !== '+') { |
| 17 | + throw new Error('Unsupported binary operator ' + ast.operator) |
| 18 | + } |
| 19 | + return evalToString(ast.left) + evalToString(ast.right) |
| 20 | + case 'TemplateLiteral': |
| 21 | + return ast.quasis.reduce( |
| 22 | + (concatenatedValue, templateElement) => |
| 23 | + concatenatedValue + templateElement.value.raw, |
| 24 | + '' |
| 25 | + ) |
| 26 | + case 'Identifier': |
| 27 | + return ast.name |
| 28 | + default: |
| 29 | + throw new Error('Unsupported type ' + ast.type) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Takes a `throw new error` statement and transforms it depending on the minify argument. Either option results in a |
| 35 | + * smaller bundle size in production for consumers. |
| 36 | + * |
| 37 | + * If minify is enabled, we'll replace the error message with just an index that maps to an arrow object lookup. |
| 38 | + * |
| 39 | + * If minify is disabled, we'll add in a conditional statement to check the process.env.NODE_ENV which will output a |
| 40 | + * an error number index in production or the actual error message in development. This allows consumers using webpak |
| 41 | + * or another build tool to have these messages in development but have just the error index in production. |
| 42 | + * |
| 43 | + * E.g. |
| 44 | + * Before: |
| 45 | + * throw new Error("This is my error message."); |
| 46 | + * throw new Error("This is a second error message."); |
| 47 | + * |
| 48 | + * After (with minify): |
| 49 | + * throw new Error(0); |
| 50 | + * throw new Error(1); |
| 51 | + * |
| 52 | + * After: (without minify): |
| 53 | + * throw new Error(node.process.NODE_ENV === 'production' ? 0 : "This is my error message."); |
| 54 | + * throw new Error(node.process.NODE_ENV === 'production' ? 1 : "This is a second error message."); |
| 55 | + */ |
| 56 | +module.exports = babel => { |
| 57 | + const t = babel.types |
| 58 | + // When the plugin starts up, we'll load in the existing file. This allows us to continually add to it so that the |
| 59 | + // indexes do not change between builds. |
| 60 | + let errorsFiles = '' |
| 61 | + if (fs.existsSync('errors.json')) { |
| 62 | + errorsFiles = fs.readFileSync('errors.json').toString() |
| 63 | + } |
| 64 | + let errors = Object.values(JSON.parse(errorsFiles || '{}')) |
| 65 | + // This variable allows us to skip writing back to the file if the errors array hasn't changed |
| 66 | + let changeInArray = false |
| 67 | + |
| 68 | + return { |
| 69 | + pre: () => { |
| 70 | + changeInArray = false |
| 71 | + }, |
| 72 | + visitor: { |
| 73 | + ThrowStatement(path, file) { |
| 74 | + const arguments = path.node.argument.arguments |
| 75 | + const minify = file.opts.minify |
| 76 | + |
| 77 | + if (arguments && arguments[0]) { |
| 78 | + // Skip running this logic when certain types come up: |
| 79 | + // Identifier comes up when a variable is thrown (E.g. throw new error(message)) |
| 80 | + // NumericLiteral, CallExpression, and ConditionalExpression is code we have already processed |
| 81 | + if ( |
| 82 | + path.node.argument.arguments[0].type === 'Identifier' || |
| 83 | + path.node.argument.arguments[0].type === 'NumericLiteral' || |
| 84 | + path.node.argument.arguments[0].type === 'ConditionalExpression' || |
| 85 | + path.node.argument.arguments[0].type === 'CallExpression' |
| 86 | + ) { |
| 87 | + return |
| 88 | + } |
| 89 | + |
| 90 | + const errorMsgLiteral = evalToString(path.node.argument.arguments[0]) |
| 91 | + |
| 92 | + if (errorMsgLiteral.includes('Super expression')) { |
| 93 | + // ignore Babel runtime error message |
| 94 | + return |
| 95 | + } |
| 96 | + |
| 97 | + // Attempt to get the existing index of the error. If it is not found, add it to the array as a new error. |
| 98 | + let errorIndex = errors.indexOf(errorMsgLiteral) |
| 99 | + if (errorIndex === -1) { |
| 100 | + errors.push(errorMsgLiteral) |
| 101 | + errorIndex = errors.length - 1 |
| 102 | + changeInArray = true |
| 103 | + } |
| 104 | + |
| 105 | + // Import the error message function |
| 106 | + // Note that all of our error messages are in `src`, so we can assume a relative path here |
| 107 | + const formatProdErrorMessageIdentifier = helperModuleImports.addDefault( |
| 108 | + path, |
| 109 | + './utils/formatProdErrorMessage', |
| 110 | + { nameHint: 'formatProdErrorMessage' } |
| 111 | + ) |
| 112 | + |
| 113 | + // Creates a function call to output the message to the error code page on the website |
| 114 | + const prodMessage = t.callExpression( |
| 115 | + formatProdErrorMessageIdentifier, |
| 116 | + [t.numericLiteral(errorIndex)] |
| 117 | + ) |
| 118 | + |
| 119 | + if (minify) { |
| 120 | + path.replaceWith( |
| 121 | + t.throwStatement( |
| 122 | + t.newExpression(t.identifier('Error'), [prodMessage]) |
| 123 | + ) |
| 124 | + ) |
| 125 | + } else { |
| 126 | + path.replaceWith( |
| 127 | + t.throwStatement( |
| 128 | + t.newExpression(t.identifier('Error'), [ |
| 129 | + t.conditionalExpression( |
| 130 | + t.binaryExpression( |
| 131 | + '===', |
| 132 | + t.identifier('process.env.NODE_ENV'), |
| 133 | + t.stringLiteral('production') |
| 134 | + ), |
| 135 | + prodMessage, |
| 136 | + path.node.argument.arguments[0] |
| 137 | + ) |
| 138 | + ]) |
| 139 | + ) |
| 140 | + ) |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + }, |
| 145 | + post: () => { |
| 146 | + // If there is a new error in the array, convert it to an indexed object and write it back to the file. |
| 147 | + if (changeInArray) { |
| 148 | + fs.writeFileSync('errors.json', JSON.stringify({ ...errors }, null, 2)) |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | +} |
0 commit comments