11const { createMacro, MacroError } = require ( 'babel-plugin-macros' ) ;
22const helperModuleImports = require ( '@babel/helper-module-imports' ) ;
33const fs = require ( 'fs' ) ;
4+ const path = require ( 'path' ) ;
45
56function invertObject ( object ) {
67 const inverted = { } ;
@@ -11,9 +12,13 @@ function invertObject(object) {
1112}
1213
1314/**
15+ * Supported imports:
16+ * 1. bare specifier e.g. `'@material-ui/utils/macros/MuiError.macro'`
17+ * 2. relative import from `packages/material-ui-utils/src` e.g. `'../macros/MuiError.macro'`
18+ *
1419 * @param {import('babel-plugin-macros').MacroParams } param0
1520 */
16- function muiError ( { references, babel, config } ) {
21+ function muiError ( { references, babel, config, source } ) {
1722 const { errorCodesPath = { } , missingError = 'annotate' } = config ;
1823 const errorCodes = JSON . parse ( fs . readFileSync ( errorCodesPath , { encoding : 'utf8' } ) ) ;
1924 const errorCodesLookup = invertObject ( errorCodes ) ;
@@ -125,13 +130,33 @@ function muiError({ references, babel, config }) {
125130 errorCode = parseInt ( errorCode , 10 ) ;
126131
127132 if ( formatMuiErrorMessageIdentifier === null ) {
128- // Outputs:
129- // import { formatMuiErrorMessage } from '@material-ui/utils';
130- formatMuiErrorMessageIdentifier = helperModuleImports . addNamed (
131- babelPath ,
132- 'formatMuiErrorMessage' ,
133- '@material-ui/utils' ,
134- ) ;
133+ const isBareImportSourceIdentifier = source . startsWith ( '@material-ui/utils' ) ;
134+ if ( isBareImportSourceIdentifier ) {
135+ // Input: import MuiError from '@material-ui/utils/macros/MuiError.macro'
136+ // Outputs:
137+ // import { formatMuiErrorMessage } from '@material-ui/utils';
138+ formatMuiErrorMessageIdentifier = helperModuleImports . addNamed (
139+ babelPath ,
140+ 'formatMuiErrorMessage' ,
141+ '@material-ui/utils' ,
142+ ) ;
143+ } else {
144+ const normalizedRelativeImport = path . normalize (
145+ source . replace ( '../macros/MuiError.macro' , './formatMuiErrorMessage' ) ,
146+ ) ;
147+ // 'formatMuiErrorMessage' implies './formatMuiErrorMessage' for fs paths but not for import specifiers.
148+ const formatMuiErrorMessageImportSource = normalizedRelativeImport . startsWith ( '.' )
149+ ? normalizedRelativeImport
150+ : `./${ normalizedRelativeImport } ` ;
151+ // Input: import MuiError from '../macros/MuiError.macro'
152+ // Outputs:
153+ // import formatMuiErrorMessage from './formatMuiErrorMessage';
154+ formatMuiErrorMessageIdentifier = helperModuleImports . addDefault (
155+ babelPath ,
156+ formatMuiErrorMessageImportSource ,
157+ { nameHint : 'formatMuiErrorMessage' } ,
158+ ) ;
159+ }
135160 }
136161
137162 // Outputs:
0 commit comments