Skip to content
Merged
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
21 changes: 21 additions & 0 deletions .changeset/afraid-meals-attend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
"@lynx-js/template-webpack-plugin": patch
"@lynx-js/react-rsbuild-plugin": patch
"@lynx-js/rspeedy": patch
---

Support `output.inlineScripts`, which controls whether to inline scripts into Lynx bundle (`.lynx.bundle`).

Only background thread scripts can remain non-inlined, whereas the main thread script is always inlined.

example:

```js
import { defineConfig } from '@lynx-js/rspeedy';

export default defineConfig({
output: {
inlineScripts: false,
},
});
```
1 change: 1 addition & 0 deletions packages/rspeedy/core/etc/rspeedy.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ export interface Output {
distPath?: DistPath | undefined;
filename?: string | Filename | undefined;
filenameHash?: boolean | string | undefined;
inlineScripts?: boolean | undefined;
legalComments?: 'none' | 'inline' | 'linked' | undefined;
minify?: Minify | boolean | undefined;
sourceMap?: boolean | SourceMap | undefined;
Expand Down
3 changes: 3 additions & 0 deletions packages/rspeedy/core/src/config/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ export function applyDefaultRspeedyConfig(config: Config): Config {
// since some plugin(e.g.: `@lynx-js/qrcode-rsbuild-plugin`) will read
// from the `output.filename.bundle` field.
filename: getFilename(config.output?.filename),

// inlineScripts should be enabled by default
inlineScripts: true,
},

tools: {
Expand Down
26 changes: 26 additions & 0 deletions packages/rspeedy/core/src/config/output/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,32 @@ export interface Output {
*/
filenameHash?: boolean | string | undefined

/**
* The {@link Output.inlineScripts} option controls whether to inline scripts into Lynx bundle (`.lynx.bundle`).
*
* @remarks
*
* If no value is provided, the default value would be `true`.
*
* This is different with {@link https://rsbuild.dev/config/output/inline-scripts | output.inlineScripts } since we normally want to inline scripts in Lynx bundle (`.lynx.bundle`).
*
* Only background thread scripts can remain non-inlined, whereas the main thread script is always inlined.
*
Comment thread
gaoachao marked this conversation as resolved.
* @example
*
* Disable inlining background thread scripts.
* ```js
* import { defineConfig } from '@lynx-js/rspeedy'
*
* export default defineConfig({
* output: {
* inlineScripts: false,
* },
* })
* ```
*/
inlineScripts?: boolean | undefined

/**
* The {@link Output.legalComments} controls how to handle the legal comment.
*
Expand Down
9 changes: 9 additions & 0 deletions packages/rspeedy/core/test/config/output.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,15 @@ describe('Config - Output', () => {
})
})

test('output.inlineScripts', () => {
assertType<Output>({
inlineScripts: true,
})
assertType<Output>({
inlineScripts: false,
})
})

test('output.legalComments', () => {
assertType<Output>({
legalComments: 'inline',
Expand Down
12 changes: 12 additions & 0 deletions packages/rspeedy/core/test/config/validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,8 @@ describe('Config Validation', () => {
{ distPath: { image: 'image' } },
{ distPath: { font: 'font' } },
{ distPath: { svg: 'svg' } },
{ inlineScripts: true },
{ inlineScripts: false },
{ legalComments: 'inline' },
{ legalComments: 'none' },
{ legalComments: 'linked' },
Expand Down Expand Up @@ -1097,6 +1099,16 @@ describe('Config Validation', () => {
]
`)

expect(() => validate({ output: { inlineScripts: null } }))
.toThrowErrorMatchingInlineSnapshot(`
[Error: Invalid configuration.

Invalid config on \`$input.output.inlineScripts\`.
- Expect to be (boolean | undefined)
- Got: null
]
`)

expect(() => validate({ output: { legalComments: [null] } }))
.toThrowErrorMatchingInlineSnapshot(`
[Error: Invalid configuration.
Expand Down
7 changes: 6 additions & 1 deletion packages/rspeedy/plugin-react/src/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,11 @@ export function applyEntry(
})

if (isLynx) {
const inlineScripts =
typeof environment.config.output?.inlineScripts === 'boolean'
? environment.config.output.inlineScripts
: true

chain
.plugin(PLUGIN_NAME_RUNTIME_WRAPPER)
.use(RuntimeWrapperWebpackPlugin, [{
Expand All @@ -222,7 +227,7 @@ export function applyEntry(
}])
.end()
.plugin(`${LynxEncodePlugin.name}`)
.use(LynxEncodePlugin, [{}])
.use(LynxEncodePlugin, [{ inlineScripts }])
Comment thread
gaoachao marked this conversation as resolved.
.end()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ export class LynxEncodePlugin {

// @public
export interface LynxEncodePluginOptions {
// (undocumented)
encodeBinary?: string;
// (undocumented)
inlineScripts?: boolean;
}

// @public
Expand Down
40 changes: 29 additions & 11 deletions packages/webpack/template-webpack-plugin/src/LynxEncodePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ import type { CSS } from './index.js';
*
* @public
*/
// biome-ignore lint/suspicious/noEmptyInterface: As expected.
export interface LynxEncodePluginOptions {}
export interface LynxEncodePluginOptions {
encodeBinary?: string;
inlineScripts?: boolean;
}

/**
* LynxEncodePlugin
Expand Down Expand Up @@ -92,6 +94,7 @@ export class LynxEncodePlugin {
static defaultOptions: Readonly<Required<LynxEncodePluginOptions>> = Object
.freeze<Required<LynxEncodePluginOptions>>({
encodeBinary: 'napi',
inlineScripts: true,
});
/**
* The entry point of a webpack plugin.
Expand Down Expand Up @@ -146,6 +149,19 @@ export class LynxEncodePluginImpl {
const { encodeData } = args;
const { manifest } = encodeData;

let publicPath = '/';
if (!this.options.inlineScripts) {
if (typeof compilation?.outputOptions.publicPath === 'function') {
compilation.errors.push(
new compiler.webpack.WebpackError(
'`publicPath` as a function is not supported yet.',
),
);
} else {
publicPath = compilation?.outputOptions.publicPath ?? '/';
}
}

if (!isDebug() && !isDev && !isRsdoctor()) {
[
encodeData.lepusCode.root,
Expand Down Expand Up @@ -178,18 +194,20 @@ export class LynxEncodePluginImpl {
Object.keys(manifest)
.map((name) =>
`module.exports=lynx.requireModule('${
this.#formatJSName(name)
this.#formatJSName(name, publicPath)
}',globDynamicComponentEntry?globDynamicComponentEntry:'__Card__')`
)
.join(','),
this.#appServiceFooter(),
].join(''),
...(Object.fromEntries(
Object.entries(manifest).map(([name, source]) => [
this.#formatJSName(name),
source,
]),
)),
...(this.options.inlineScripts
? Object.fromEntries(
Object.entries(manifest).map(([name, source]) => [
this.#formatJSName(name, publicPath),
source,
]),
)
: {}),
};

return args;
Expand Down Expand Up @@ -230,8 +248,8 @@ export class LynxEncodePluginImpl {
return amdFooter + loadScriptFooter;
}

#formatJSName(name: string): string {
return `/${name}`;
#formatJSName(name: string, publicPath: string): string {
return publicPath + name;
}

protected options: Required<LynxEncodePluginOptions>;
Expand Down
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,46 @@
/*
// 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:main-thread' */
'./foo.js'
);
expect(foo()).toBe(42);

const fooBackground = await import(
/* webpackChunkName: 'foo:background' */
'./foo.js'
);
expect(fooBackground.foo()).toBe(42);
});

it('manifest only contains /app-service.js', async () => {
const tasmJSONPath = resolve(__dirname, '.rspeedy/async/foo/tasm.json');
expect(existsSync(tasmJSONPath)).toBeTruthy();

const content = await readFile(tasmJSONPath, 'utf-8');
const { sourceContent, manifest } = JSON.parse(content);
const output = resolve(__dirname, 'foo:background.rspack.bundle.js');
expect(existsSync(output));

const outputContent = await readFile(output, 'utf-8');
expect(outputContent).toContain(['function', 'foo()'].join(' '));

expect(sourceContent).toHaveProperty('appType', 'DynamicComponent');

expect(manifest).not.toHaveProperty('/foo:background.rspack.bundle.js');
expect(manifest).toHaveProperty('/app-service.js');

expect(manifest['/app-service.js']).toContain(
`lynx.requireModule('/foo:background.rspack.bundle.js',globDynamicComponentEntry?globDynamicComponentEntry:'__Card__')`,
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { LynxEncodePlugin, LynxTemplatePlugin } from '../../../../src';

/** @type {import('@rspack/core').Configuration} */
export default {
devtool: false,
mode: 'development',
plugins: [
new LynxEncodePlugin({
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(':main-thread', '')
.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,37 @@
/*
// 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:main-thread' */
'./foo.js'
);
expect(foo()).toBe(42);

const fooBackground = await import(
/* webpackChunkName: 'foo:background' */
'./foo.js'
);
expect(fooBackground.foo()).toBe(42);
});

it('should generate correct foo template', async () => {
const tasmJSONPath = resolve(__dirname, '.rspeedy/async/foo/tasm.json');
expect(existsSync(tasmJSONPath)).toBeTruthy();

const content = await readFile(tasmJSONPath, 'utf-8');
const { sourceContent, manifest } = JSON.parse(content);
expect(sourceContent).toHaveProperty('appType', 'DynamicComponent');
expect(manifest).toHaveProperty(
'/foo:background.rspack.bundle.js',
expect.stringContaining('function foo()'),
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { LynxEncodePlugin, LynxTemplatePlugin } from '../../../../src';

/** @type {import('@rspack/core').Configuration} */
export default {
devtool: false,
mode: 'development',
plugins: [
new LynxEncodePlugin({
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(':main-thread', '')
.replace(':background', ''),
);
});
},
],
};
Loading