Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
5e61905
feat: server bundle mode
sylingd Jan 29, 2026
7fdb7d3
feat: server plugins
sylingd Jan 29, 2026
22a9a2f
fix: fs-extra in esm
sylingd Jan 29, 2026
c745987
chore: remove unused third party libs
sylingd Jan 30, 2026
b86c0bd
fix: fs-extra
sylingd Jan 30, 2026
81cfedc
feat: bff in bundle mode
sylingd Jan 30, 2026
1ad6ac1
fix: server-module-loader
sylingd Jan 30, 2026
f368fd6
fix: server bundle build
sylingd Jan 30, 2026
8c2f3b1
chore: remove prebundle browserslist
sylingd Jan 30, 2026
fcfda24
fix: builder plugins
sylingd Jan 30, 2026
16f71f4
test: add server bundle
sylingd Jan 31, 2026
85abfdf
Merge branch 'main' into feat/server-bundle
sylingd Jan 31, 2026
748d06a
revert: loaderContext
sylingd Jan 31, 2026
ae96df7
chore: changesety
sylingd Jan 31, 2026
8b12346
chore: add comments
sylingd Jan 31, 2026
5335dae
revert: node server
sylingd Jan 31, 2026
f99eb12
chore: remove forceESM
sylingd Jan 31, 2026
165b088
test: pure esm deploy
sylingd Jan 31, 2026
bbf837c
test: pure esm bundleServer
sylingd Jan 31, 2026
92d0fff
feat: pure esm server
sylingd Jan 31, 2026
c548b55
fix: test
sylingd Jan 31, 2026
be782c7
chore: ignore kill error
sylingd Jan 31, 2026
e3a0afa
fix: test
sylingd Jan 31, 2026
3e35ffb
fix: ut
sylingd Jan 31, 2026
7d625ad
chore: move bundled
sylingd Feb 1, 2026
791267a
chore: message
sylingd Feb 1, 2026
24e862f
Merge branch 'main' into feat/server-bundle
sylingd Mar 17, 2026
333ea5b
chore: remove handler
sylingd Mar 17, 2026
d3d0d1e
fix: bundle
sylingd Mar 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/slick-bugs-repair.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@modern-js/plugin-data-loader': minor
'@modern-js/runtime': minor
'@modern-js/app-tools': minor
'@modern-js/prod-server': minor
'@modern-js/bff-core': minor
'@modern-js/plugin-bff': minor
'@modern-js/plugin': minor
'@modern-js/server': minor
'@modern-js/types': minor
'@modern-js/utils': minor
'@modern-js/server-core': minor
---

feat: bundle server-side codes into a single file
feat: 打包服务端代码至单一文件
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ playground/


.output/
.output-server-bundle/
.vercel/
.netlify/

Expand Down
8 changes: 7 additions & 1 deletion packages/cli/plugin-bff/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
SHARED_DIR,
normalizeOutputPath,
} from '@modern-js/utils';
import { SERVER_BUNDLE_NAME } from '@modern-js/utils/universal/constants';
import type { ConfigChain } from '@rsbuild/core';
import clientGenerator from './utils/clientGenerator';
import pluginGenerator from './utils/pluginGenerator';
Expand Down Expand Up @@ -180,7 +181,10 @@ export const bffPlugin = (): CliPlugin<AppTools> => ({
devServer: {
compress,
},
bundlerChain: (chain, { CHAIN_ID, isServer }) => {
bundlerChain: (
chain,
{ CHAIN_ID, isServer: rIsServer, environment },
) => {
const { port, appDirectory, apiDirectory, lambdaDirectory } =
api.getAppContext();
const modernConfig = api.getNormalizedConfig();
Expand All @@ -204,6 +208,8 @@ export const bffPlugin = (): CliPlugin<AppTools> => ({
normalizeOutputPath(`${apiDirectory}${path.sep}.*(.[tj]s)$`),
);

const isServer =
rIsServer || environment.name === SERVER_BUNDLE_NAME;
const name = isServer ? 'server' : 'client';
const sourceExt =
process.env.MODERN_LIB_FORMAT === 'esm' ? 'mjs' : 'js';
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/plugin-bff/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,14 @@ export default (): ServerPlugin => ({
const { pwd, prefix, httpMethodDecider } = input;
const apiDir = path.resolve(pwd, API_DIR);
const appContext = api.getServerContext();
const { apiDirectory, lambdaDirectory } = appContext;
const { apiDirectory, lambdaDirectory, dependencies } = appContext;
apiRouter = new ApiRouter({
appDir: pwd,
apiDir: (apiDirectory as string) || apiDir,
lambdaDir: lambdaDirectory as string,
prefix,
httpMethodDecider,
dependencies,
});
const apiHandlerInfos = await apiRouter.getApiHandlers();
api.updateServerContext({
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/plugin-data-loader/src/cli/loader.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { promisify } from 'util';
import { logger } from '@modern-js/utils';
import { SERVER_BUNDLE_NAME } from '@modern-js/utils/universal/constants';
import type { Rspack } from '@rsbuild/core';
import { generateClient } from './generateClient';

Expand All @@ -19,6 +20,7 @@ export default async function loader(
) {
this.cacheable();
const target = this._compiler?.options.target;
const name = this._compiler?.options.name;

const shouldSkip = (compileTarget: string) => {
return (
Expand All @@ -28,6 +30,7 @@ export default async function loader(
};

if (
name === SERVER_BUNDLE_NAME ||
shouldSkip('node') ||
shouldSkip('webworker') ||
shouldSkip('async-node')
Expand Down
19 changes: 1 addition & 18 deletions packages/runtime/plugin-runtime/src/cli/constants.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1 @@
export const APP_FILE_NAME = 'App';

export const ENTRY_POINT_FILE_NAME = 'index.jsx';

export const SERVER_ENTRY_POINT_FILE_NAME = 'index.server.jsx';

export const INDEX_FILE_NAME = 'index';

export const ENTRY_BOOTSTRAP_FILE_NAME = 'bootstrap.jsx';

export const ENTRY_SERVER_BOOTSTRAP_FILE_NAME = 'bootstrap.server.jsx';

export const ENTRY_POINT_RUNTIME_REGISTER_FILE_NAME = 'runtime-register.js';

export const ENTRY_POINT_RUNTIME_GLOBAL_CONTEXT_FILE_NAME =
'runtime-global-context';

export const ENTRY_POINT_REGISTER_FILE_NAME = 'register.js';
export * from '@modern-js/utils/cli/constants';
5 changes: 4 additions & 1 deletion packages/runtime/plugin-runtime/src/cli/ssr/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {
import type { CLIPluginAPI } from '@modern-js/plugin';
import type { Entrypoint } from '@modern-js/types';
import { LOADABLE_STATS_FILE, isUseSSRBundle } from '@modern-js/utils';
import { SERVER_BUNDLE_NAME } from '@modern-js/utils/universal/constants';
import type { RsbuildPlugin } from '@rsbuild/core';
import LoadableBundlerPlugin from './loadable-bundler-plugin';
import { resolveSSRMode } from './mode';
Expand Down Expand Up @@ -83,7 +84,9 @@ const ssrBuilderPlugin = (
setup(api) {
api.modifyEnvironmentConfig((config, { name, mergeEnvironmentConfig }) => {
const isServerEnvironment =
config.output.target === 'node' || name === 'workerSSR';
config.output.target === 'node' ||
name === 'workerSSR' ||
name === SERVER_BUNDLE_NAME;
const userConfig = modernAPI.getNormalizedConfig();

// Maybe we can enable it for node 18 and above, but we can't ensure it in the compilation.
Expand Down
4 changes: 3 additions & 1 deletion packages/runtime/plugin-runtime/src/common.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import type { RuntimePlugin } from './core/plugin';

export const isBrowser = () =>
typeof window !== 'undefined' && window.name !== 'nodejs';
typeof window !== 'undefined' &&
window.name !== 'nodejs' &&
typeof document !== 'undefined';

export interface RuntimeConfig {
plugins?: RuntimePlugin[];
Expand Down
4 changes: 1 addition & 3 deletions packages/runtime/plugin-runtime/src/core/server/helmet.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// 用于 react-helmet 正则替换
import { EOL } from 'os';
import type { HelmetData } from 'react-helmet';
import { safeReplace } from './utils';

Expand Down Expand Up @@ -54,7 +52,7 @@ export function helmetReplace(content: string, helmetData: HelmetData) {
style,
!existTitleTag ? title : '',
].reduce((pre, cur) => {
return pre + (cur.length > 0 ? ` ${cur}${EOL}` : '');
return pre + (cur.length > 0 ? ` ${cur}\n` : '');
}, '');

return safeReplace(result, RE_LAST_IN_HEAD, `${helmetStr}</head>`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ export const walk = async (options: {
let splatData = '';
let splatAction = '';

const items = await fs.readdir(dirname);
const items = (await fs.readdir(dirname)).sort();

for (const item of items) {
const itemPath = path.join(dirname, item);
Expand Down
1 change: 1 addition & 0 deletions packages/server/bff-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"test": "rstest --passWithNoTests"
},
"dependencies": {
"@modern-js/server-core": "workspace:*",
"@modern-js/utils": "workspace:*",
"@swc/helpers": "^0.5.17",
"koa-compose": "^4.1.0",
Expand Down
55 changes: 49 additions & 6 deletions packages/server/bff-core/src/router/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import path from 'path';
import { fs, logger } from '@modern-js/utils';
import 'reflect-metadata';
import { getBundledDep } from '@modern-js/server-core/bundled';
import type { HttpMethodDecider } from '@modern-js/types';
import { HttpMethod, OperatorType, TriggerType, httpMethods } from '../types';
import { INPUT_PARAMS_DECIDER, debug } from '../utils';
Expand All @@ -13,6 +14,7 @@ import type { APIHandlerInfo, ApiHandler, ModuleInfo } from './types';
import {
getFiles,
getPathFromFilename,
interopHandlerModule,
requireHandlerModule,
sortRoutes,
} from './utils';
Expand All @@ -38,31 +40,47 @@ export class ApiRouter {

private isBuild?: boolean;

private dependencies?: Record<string, Promise<any>>;

constructor({
appDir,
apiDir,
lambdaDir,
prefix,
isBuild,
httpMethodDecider = 'functionName',
dependencies,
}: {
appDir?: string;
apiDir: string;
lambdaDir?: string;
prefix?: string;
isBuild?: boolean;
httpMethodDecider?: HttpMethodDecider;
dependencies?: Record<string, Promise<any>>;
}) {
this.validateAbsolute(apiDir, 'apiDir');
this.validateAbsolute(lambdaDir, 'lambdaDir');

this.prefix = this.initPrefix(prefix);
this.appDir = appDir;
this.apiDir = apiDir;
this.httpMethodDecider = httpMethodDecider;
this.isBuild = isBuild;
this.lambdaDir = this.getExactLambdaDir(this.apiDir, lambdaDir);
this.existLambdaDir = fs.existsSync(this.lambdaDir);

if (process.env.MODERN_SERVER_BUNDLE) {
if (lambdaDir && dependencies) {
this.dependencies = dependencies;
this.existLambdaDir = Object.keys(dependencies).some(x =>
x.startsWith(lambdaDir),
);
} else {
this.existLambdaDir = false;
}
} else {
this.validateAbsolute(apiDir, 'apiDir');
this.validateAbsolute(lambdaDir, 'lambdaDir');
this.existLambdaDir = fs.existsSync(this.lambdaDir);
}

debug(`apiDir:`, this.apiDir, `lambdaDir:`, this.lambdaDir);
}

Expand Down Expand Up @@ -214,8 +232,20 @@ export class ApiRouter {
if (!this.existLambdaDir) {
return [];
}
const apiFiles = (this.apiFiles = getFiles(this.lambdaDir, API_FILE_RULES));
return apiFiles;
if (process.env.MODERN_SERVER_BUNDLE) {
if (!this.dependencies) {
return [];
}
return Object.keys(this.dependencies).filter(x =>
x.startsWith(this.lambdaDir),
);
} else {
const apiFiles = (this.apiFiles = getFiles(
this.lambdaDir,
API_FILE_RULES,
));
return apiFiles;
}
}

public getApiFiles() {
Expand Down Expand Up @@ -268,6 +298,19 @@ export class ApiRouter {
}

private async getModuleInfo(filename: string) {
if (process.env.MODERN_SERVER_BUNDLE) {
if (!this.dependencies) {
return null;
}
const mod = await getBundledDep(filename, this.dependencies);
if (mod) {
return {
filename,
module: interopHandlerModule(mod),
};
}
return null;
}
try {
const module = await requireHandlerModule(filename);
return {
Expand Down
10 changes: 5 additions & 5 deletions packages/server/bff-core/src/router/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,12 @@ export const isHandler = (input: any): input is Handler<any, any> =>
const isFunction = (input: any): input is (...args: any) => any =>
input && {}.toString.call(input) === '[object Function]';

export const interopHandlerModule = (mod: any) =>
isFunction(mod) ? { default: mod } : mod;

export const requireHandlerModule = async (modulePath: string) => {
const module = await compatibleRequire(modulePath, false);
if (isFunction(module)) {
return { default: module };
}
return module;
const mod = await compatibleRequire(modulePath, false);
return interopHandlerModule(mod);
};

const routeValue = (routePath: string) => {
Expand Down
12 changes: 12 additions & 0 deletions packages/server/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@
},
"default": "./dist/cjs/adapters/node/index.js"
},
"./bundled": {
"types": "./dist/types/adapters/bundled/index.d.ts",
"modern:source": "./src/adapters/bundled/index.ts",
"node": {
"import": "./dist/esm-node/adapters/bundled/index.mjs",
"require": "./dist/cjs/adapters/bundled/index.js"
},
"default": "./dist/cjs/adapters/bundled/index.js"
},
"./hono": {
"types": "./dist/types/hono.d.ts",
"node": {
Expand All @@ -54,6 +63,9 @@
"node": [
"./dist/types/adapters/node/index.d.ts"
],
"bundled": [
"./dist/types/adapters/bundled/index.d.ts"
],
"hono": [
"./dist/types/hono.d.ts"
]
Expand Down
38 changes: 38 additions & 0 deletions packages/server/core/src/adapters/bundled/helper/getBundledDep.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
export const getBundledDep = async <T = any>(
keyParam: string,
deps?: Record<string, Promise<any>>,
interop = true,
): Promise<T | undefined> => {
if (!deps || typeof deps !== 'object') {
return;
}

let key = keyParam.replace(/\\/g, '/');
if (key.startsWith('/')) {
key = key.substring(1);
}

let value: any;
if (deps.hasOwnProperty(key)) {
value = deps[key];
} else {
const s = ['.js', '.json', '.mjs'].find(x => deps.hasOwnProperty(key + x));
if (s) {
value = deps[s];
}
}

if (typeof value !== 'function') {
return;
}

try {
const res = await value();
if (interop) {
return res.default || res;
}
return res;
} catch (e) {
console.error(e);
}
};
6 changes: 6 additions & 0 deletions packages/server/core/src/adapters/bundled/helper/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export {
loadBundledServerRuntimeConfig,
loadBundledServerCliConfig,
} from './loadConfig';
export { loadBundledCacheConfig } from './loadCache';
export { getBundledDep } from './getBundledDep';
Loading
Loading