import type { Plugin } from 'vite' ; import MagicString from 'magic-string' ; import { createFilter } from '@rollup/pluginutils' ; export default ( locales ) : Plugin => { let entryJs = '' ; const include = [ '**/*.ts' , '**/*.js' , '**/*.tsx' , '**/*.jsx' ] ; const exclude = 'node_modules/**' ; const momentRegex = /moment[/\\]locale[/\\]/ ; const filter = createFilter ( include , exclude ) ; const momentLocales = typeof locales === 'string' ? [ locales ] : locales ; let needSourcemap = false ; return { name : 'vite-plugin-moment' , enforce : 'pre' , configResolved ( resolvedConfig ) { needSourcemap = ! ! resolvedConfig . build . sourcemap ; } , resolveId ( id ) { if ( id . match ( momentRegex ) ) { return id . replace ( momentRegex , 'moment/dist/locale/' ) ; } } , transform ( code , id ) { if ( ! entryJs && filter ( id ) ) { entryJs = id ; } if ( entryJs === id && momentLocales ) { let s ; const str = ( ) => s || ( s = new MagicString ( code ) ) ; str ( ) . prependLeft ( 0 , `${ momentLocales . map ( ( locale ) => `import 'moment/dist/locale/${ locale }';` ) . join ( '\n' ) }\n` ) ; return { map : needSourcemap ? str ( ) . generateMap ( { hires : true } ) : null , code : str ( ) . toString ( ) , } ; } return null ; } } ; } ;