11import type { ServerPlugin } from '@modern-js/server-runtime' ;
2- import { createStaticMiddleware } from './staticMiddleware' ;
2+ import {
3+ createCorsMiddleware ,
4+ createStaticMiddleware ,
5+ } from './staticMiddleware' ;
36
47const staticServePlugin = ( ) : ServerPlugin => ( {
58 name : '@modern-js/module-federation/server' ,
69 setup : ( api ) => {
710 api . onPrepare ( ( ) => {
811 // In development, we don't need to serve the manifest file, bundler dev server will handle it
9- console . log ( process . env . NODE_ENV ) ;
1012 if ( process . env . NODE_ENV === 'development' ) {
1113 return ;
1214 }
@@ -15,21 +17,30 @@ const staticServePlugin = (): ServerPlugin => ({
1517 const config = api . getServerConfig ( ) ;
1618
1719 const assetPrefix = config . output ?. assetPrefix || '' ;
18- if ( ! config . server ?. ssr ) {
19- return ;
20+ // When SSR is enabled, we need to serve the files in `bundle/` directory externally
21+ // Modern.js will only serve the files in `static/` directory
22+ if ( config . server ?. ssr ) {
23+ const context = api . getServerContext ( ) ;
24+ const pwd = context . distDirectory ! ;
25+ const serverStaticMiddleware = createStaticMiddleware ( {
26+ assetPrefix,
27+ pwd,
28+ } ) ;
29+ middlewares . push ( {
30+ name : 'module-federation-serve-manifest' ,
31+ handler : serverStaticMiddleware ,
32+ } ) ;
2033 }
2134
22- const context = api . getServerContext ( ) ;
23- const pwd = context . distDirectory ! ;
24-
25- const serverStaticMiddleware = createStaticMiddleware ( {
26- assetPrefix,
27- pwd,
28- } ) ;
29- middlewares . push ( {
30- name : 'module-federation-serve-manifest' ,
31- handler : serverStaticMiddleware ,
32- } ) ;
35+ // When the MODERN_MF_AUTO_CORS environment variable is set, the server will add CORS headers to the response
36+ // This environment variable should only be set when running `serve` command in local test.
37+ if ( process . env . MODERN_MF_AUTO_CORS ) {
38+ const corsMiddleware = createCorsMiddleware ( ) ;
39+ middlewares . push ( {
40+ name : 'module-federation-cors' ,
41+ handler : corsMiddleware ,
42+ } ) ;
43+ }
3344 } ) ;
3445 } ,
3546} ) ;
0 commit comments