77 */
88
99import { lookup as lookupMimeType } from 'mrmime' ;
10+ import { readFileSync } from 'node:fs' ;
1011import { extname } from 'node:path' ;
1112import type { Connect , ViteDevServer } from 'vite' ;
1213import { AngularMemoryOutputFiles , AngularOutputAssets , pathnameWithoutBasePath } from '../utils' ;
@@ -17,6 +18,8 @@ export interface ComponentStyleRecord {
1718 reload ?: boolean ;
1819}
1920
21+ const JS_TS_REGEXP = / \. [ c m ] ? [ t j ] s x ? $ / ;
22+
2023export function createAngularAssetsMiddleware (
2124 server : ViteDevServer ,
2225 assets : AngularOutputAssets ,
@@ -38,15 +41,20 @@ export function createAngularAssetsMiddleware(
3841 // Rewrite all build assets to a vite raw fs URL
3942 const asset = assets . get ( pathname ) ;
4043 if ( asset ) {
41- // Workaround to disable Vite transformer middleware.
42- // See: https://github.com/vitejs/vite/blob/746a1daab0395f98f0afbdee8f364cb6cf2f3b3f/packages/vite/src/node/server/middlewares/transform.ts#L201 and
43- // https://github.com/vitejs/vite/blob/746a1daab0395f98f0afbdee8f364cb6cf2f3b3f/packages/vite/src/node/server/transformRequest.ts#L204-L206
44- req . headers . accept = 'text/html' ;
45-
46- // The encoding needs to match what happens in the vite static middleware.
47- // ref: https://github.com/vitejs/vite/blob/d4f13bd81468961c8c926438e815ab6b1c82735e/packages/vite/src/node/server/middlewares/static.ts#L163
48- req . url = `${ server . config . base } @fs/${ encodeURI ( asset . source ) } ` ;
49- next ( ) ;
44+ // This is a workaround to serve JS and TS files without Vite transformations.
45+ if ( JS_TS_REGEXP . test ( extension ) ) {
46+ const mimeType = lookupMimeType ( extension ) ;
47+ if ( mimeType ) {
48+ res . setHeader ( 'Content-Type' , mimeType ) ;
49+ }
50+ res . setHeader ( 'Cache-Control' , 'no-cache' ) ;
51+ res . end ( readFileSync ( asset . source ) ) ;
52+ } else {
53+ // The encoding needs to match what happens in the vite static middleware.
54+ // ref: https://github.com/vitejs/vite/blob/d4f13bd81468961c8c926438e815ab6b1c82735e/packages/vite/src/node/server/middlewares/static.ts#L163
55+ req . url = `${ server . config . base } @fs/${ encodeURI ( asset . source ) } ` ;
56+ next ( ) ;
57+ }
5058
5159 return ;
5260 }
0 commit comments