Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 9 additions & 1 deletion packages/rspeedy/plugin-react/src/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,9 +241,17 @@ export function applyEntry(
}

if (isWeb) {
let inlineScripts
if (experimental_isLazyBundle) {
// TODO: support inlineScripts in lazyBundle
inlineScripts = true
} else {
inlineScripts = environment.config.output?.inlineScripts ?? true
}

chain
.plugin(PLUGIN_NAME_WEB)
.use(WebEncodePlugin, [])
.use(WebEncodePlugin, [{ inlineScripts }])
.end()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,17 +171,32 @@ export interface TemplateHooks {
//
// @public (undocumented)
export class WebEncodePlugin {
constructor(options?: WebEncodePluginOptions);
// (undocumented)
apply(compiler: Compiler): void;
// (undocumented)
static BEFORE_ENCODE_HOOK_STAGE: number;
// (undocumented)
static defaultOptions: Readonly<Required<WebEncodePluginOptions>>;
deleteDebuggingAssets(compilation: Compilation, assets: ({
name: string;
} | undefined)[]): void;
// (undocumented)
static ENCODE_HOOK_STAGE: number;
// (undocumented)
static name: string;
// (undocumented)
protected options: Required<WebEncodePluginOptions>;
}

// @public
export interface WebEncodePluginOptions {
// (undocumented)
encodeBinary?: string;
// Warning: (ae-forgotten-export) The symbol "InlineChunkConfig_2" needs to be exported by the entry point index.d.ts
//
// (undocumented)
inlineScripts?: InlineChunkConfig_2 | undefined;
}

// Warnings were encountered during analysis:
Expand Down
79 changes: 77 additions & 2 deletions packages/webpack/template-webpack-plugin/src/WebEncodePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,42 @@ import {
} from './LynxTemplatePlugin.js';
import { genStyleInfo } from './web/genStyleInfo.js';

// https://github.com/web-infra-dev/rsbuild/blob/main/packages/core/src/types/config.ts#L1029
type InlineChunkTestFunction = (params: {
size: number;
name: string;
}) => boolean;
type InlineChunkTest = RegExp | InlineChunkTestFunction;
type InlineChunkConfig = boolean | InlineChunkTest | {
enable?: boolean | 'auto';
test: InlineChunkTest;
};

/**
* The options for WebEncodePluginOptions
*
* @public
*/
export interface WebEncodePluginOptions {
encodeBinary?: string;
inlineScripts?: InlineChunkConfig | undefined;
}

export class WebEncodePlugin {
static name = 'WebEncodePlugin';
static BEFORE_ENCODE_HOOK_STAGE = 100;
static ENCODE_HOOK_STAGE = 100;

static defaultOptions: Readonly<Required<WebEncodePluginOptions>> = Object
.freeze<Required<WebEncodePluginOptions>>({
encodeBinary: 'napi',
inlineScripts: true,
});

constructor(options: WebEncodePluginOptions = {}) {
this.options = { ...WebEncodePlugin.defaultOptions, ...options };
}

apply(compiler: Compiler): void {
const isDev = process.env['NODE_ENV'] === 'development'
|| compiler.options.mode === 'development';
Expand Down Expand Up @@ -50,13 +81,33 @@ export class WebEncodePlugin {
}, (encodeOptions) => {
const { encodeData } = encodeOptions;
const { cssMap } = encodeData.css;
const { manifest } = encodeData;
const styleInfo = genStyleInfo(cssMap);

const [name, content] = last(Object.entries(encodeData.manifest))!;
const [, content] = last(Object.entries(manifest))!;

// Determine which assets should be inlined vs external
const inlinedAssetNames = new Set<string>();
const externalAssetNames = new Set<string>();

Object.keys(manifest).forEach(manifestName => {
const assert = compilation.getAsset(manifestName);
const shouldInline = this.#shouldInlineScript(
manifestName,
assert!.source.size(),
);

if (shouldInline) {
inlinedAssetNames.add(manifestName);
} else {
externalAssetNames.add(manifestName);
}
});

if (!isDebug() && !isDev && !isRsdoctor()) {
[
{ name },
// Only add inlined assets to the deletion list
...Array.from(inlinedAssetNames).map(name => ({ name })),
encodeData.lepusCode.root,
...encodeData.lepusCode.chunks,
...encodeData.css.chunks,
Expand Down Expand Up @@ -119,6 +170,30 @@ export class WebEncodePlugin {
return compilation.deleteAsset(name);
}
}

#shouldInlineScript(name: string, size: number): boolean {
const inlineConfig = this.options.inlineScripts;

if (inlineConfig instanceof RegExp) {
return inlineConfig.test(name);
}

if (typeof inlineConfig === 'function') {
return inlineConfig({ size, name });
}

if (typeof inlineConfig === 'object') {
if (inlineConfig.enable === false) return false;
if (inlineConfig.test instanceof RegExp) {
return inlineConfig.test.test(name);
}
return inlineConfig.test({ size, name });
}

return inlineConfig !== false;
}

protected options: Required<WebEncodePluginOptions>;
}

function last<T>(array: T[]): T | undefined {
Expand Down
1 change: 1 addition & 0 deletions packages/webpack/template-webpack-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ export type {
export { LynxEncodePlugin } from './LynxEncodePlugin.js';
export type { LynxEncodePluginOptions } from './LynxEncodePlugin.js';
export { WebEncodePlugin } from './WebEncodePlugin.js';
export type { WebEncodePluginOptions } from './WebEncodePlugin.js';
export * as CSSPlugins from './css/plugins/index.js';
export * as CSS from './css/index.js';
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function foo() {
return 42;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
// Copyright 2024 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.
*/
/// <reference types="vitest/globals" />

import { existsSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';

it('should have correct chunk content', async () => {
const { foo } = await import(
/* webpackChunkName: 'foo:background' */
'./foo.js'
);
expect(foo()).toBe(42);
});

it('should generate correct web template with external scripts', async () => {
const outputPath = resolve(__dirname, 'main.bundle');
expect(existsSync(outputPath)).toBeTruthy();

const content = await readFile(outputPath, 'utf-8');
const bundleData = JSON.parse(content);

expect(bundleData).toHaveProperty('manifest');
expect(bundleData.manifest).toHaveProperty('/app-service.js');

// Check that external script file exists (this means scripts were not inlined)
const externalScriptPath = resolve(
__dirname,
'foo:background.rspack.bundle.js',
);
expect(existsSync(externalScriptPath)).toBeTruthy();

const externalContent = await readFile(externalScriptPath, 'utf-8');
expect(externalContent).toContain('function foo()');
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { LynxTemplatePlugin, WebEncodePlugin } from '../../../../src';

/** @type {import('@rspack/core').Configuration} */
export default {
devtool: false,
mode: 'development',
plugins: [
new WebEncodePlugin({
inlineScripts: false,
}),
new LynxTemplatePlugin({
...LynxTemplatePlugin.defaultOptions,
intermediate: '.rspeedy/main',
}),
/**
* @param {import('@rspack/core').Compiler} compiler - Rspack Compiler
*/
(compiler) => {
compiler.hooks.thisCompilation.tap('test', (compilation) => {
const hooks = LynxTemplatePlugin.getLynxTemplatePluginHooks(
compilation,
);
hooks.asyncChunkName.tap(
'test',
chunkName =>
chunkName
.replace(':background', ''),
);
});
},
],
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function foo() {
return 42;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
// Copyright 2024 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.
*/
/// <reference types="vitest/globals" />

import { existsSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';

it('should have correct chunk content', async () => {
const { foo } = await import(
/* webpackChunkName: 'foo:background' */
'./foo.js'
);
expect(foo()).toBe(42);
});

it('should generate correct web template with inlined scripts', async () => {
const outputPath = resolve(__dirname, 'main.bundle');
expect(existsSync(outputPath)).toBeTruthy();

const content = await readFile(outputPath, 'utf-8');
const bundleData = JSON.parse(content);

expect(bundleData).toHaveProperty('manifest');
expect(bundleData.manifest).toHaveProperty('/app-service.js');

// When inlineScripts is true, the script content should be inlined
expect(bundleData.manifest['/app-service.js']).toContain('function foo()');
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { LynxTemplatePlugin, WebEncodePlugin } from '../../../../src';

/** @type {import('@rspack/core').Configuration} */
export default {
devtool: false,
mode: 'development',
plugins: [
new WebEncodePlugin({
inlineScripts: true,
}),
new LynxTemplatePlugin({
...LynxTemplatePlugin.defaultOptions,
intermediate: '.rspeedy/main',
}),
/**
* @param {import('@rspack/core').Compiler} compiler - Rspack Compiler
*/
(compiler) => {
compiler.hooks.thisCompilation.tap('test', (compilation) => {
const hooks = LynxTemplatePlugin.getLynxTemplatePluginHooks(
compilation,
);
hooks.asyncChunkName.tap(
'test',
chunkName =>
chunkName
.replace(':background', ''),
);
});
},
],
};