Skip to content

Instantly share code, notes, and snippets.

@brandonkramer
Last active April 17, 2022 23:06
Show Gist options
  • Save brandonkramer/1d515ba1dba9824ce9333a6acfaa0b3a to your computer and use it in GitHub Desktop.
Save brandonkramer/1d515ba1dba9824ce9333a6acfaa0b3a to your computer and use it in GitHub Desktop.
This ViteJS plugin will make sure compiled CSS files will have the same path structure as JS files which allows you to retain the same input path structure as output path
import path from 'path'
export default (cssBundleNameIndex = []) => ({
/**
* @see https://rollupjs.org/guide/en/#renderchunk
*/
renderChunk(code, chunkInfo) {
const {
fileName: jsFileName,
viteMetadata: { importedCss }
} = chunkInfo;
const hasCssFile = importedCss.size === 1;
if ( hasCssFile ) {
const originName = importedCss.values().next().value;
const newName = originName.replace( 'assets/', path.parse( jsFileName ).dir + '/' );
cssBundleNameIndex[originName] = newName;
importedCss.delete( originName );
importedCss.add( newName );
}
},
/**
* @see https://rollupjs.org/guide/en/#generatebundle
*/
generateBundle(options, bundle) {
Object.entries( bundle ).forEach( ([originName, moduleInfo]) => {
const isCssBundle = originName.endsWith( '.css' );
const isInBundleIndex = originName in cssBundleNameIndex
moduleInfo.fileName = isCssBundle && isInBundleIndex
? cssBundleNameIndex[originName]
: moduleInfo.fileName
} );
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment