Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add build option: generatePreloadJsList #56

Merged
merged 3 commits into from
Feb 22, 2024
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
4 changes: 4 additions & 0 deletions .api/public.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
declare module "@cocos/ccbuild" {

Check warning on line 1 in .api/public.d.ts

View workflow job for this annotation

GitHub Actions / test

File ignored by default.
/**
* @group Merged Types
*/
Expand Down Expand Up @@ -122,6 +122,10 @@
* @default false
*/
preserveType?: boolean;
/**
* Whether to generate a json file that contains all output script file paths.
*/
generatePreloadJsList?: boolean;
}
export interface Result {
/**
Expand Down
17 changes: 16 additions & 1 deletion modules/build-engine/src/engine-js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import { externalWasmLoader } from './rollup-plugins/external-wasm-loader';
import { StatsQuery } from '@ccbuild/stats-query';
import { filePathToModuleRequest } from '@ccbuild/utils';
import { rpNamedChunk } from './rollup-plugins/systemjs-named-register-plugin';

// import babel
import babel = Transformer.core;
Expand Down Expand Up @@ -173,7 +174,7 @@
presetEnvOptions.targets = options.targets;
}

const babelPlugins: any[] = [];

Check warning on line 177 in modules/build-engine/src/engine-js/index.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected any. Specify a different type
if (!options.targets) {
babelPlugins.push([babelPluginTransformForOf, {
loose: true,
Expand Down Expand Up @@ -252,7 +253,7 @@

{
name: '@cocos/ccbuild|module-overrides',
resolveId(source, importer): string | null {

Check warning on line 256 in modules/build-engine/src/engine-js/index.ts

View workflow job for this annotation

GitHub Actions / test

'importer' is defined but never used
if (moduleOverrides[source]) {
return source;
} else {
Expand Down Expand Up @@ -301,9 +302,14 @@
skipPreflightCheck: true,
...babelOptions,
}),

);

// The named-registered format of `System.register('cocos-js/cc.js', [], function() {...})` needs to be generated when the feature of preloading JS list is enabled.
// Otherwise, we will generate the default register code without name like `System.register([], function() {...})`.
if (options.generatePreloadJsList) {
rollupPlugins.push(rpNamedChunk());
}

// if (options.progress) {
// rollupPlugins.unshift(rpProgress());
// }
Expand Down Expand Up @@ -433,8 +439,13 @@

const rollupOutput = await rollupBuild.write(rollupOutputOptions);

const outputJSFileNames = [];
const validEntryChunks: Record<string, string> = {};
for (const output of rollupOutput.output) {
if (options.generatePreloadJsList && output.fileName.endsWith('js')) {
outputJSFileNames.push(output.fileName);
}

if (output.type === 'chunk') {
if (output.isEntry) {
const chunkName = output.name;
Expand All @@ -445,6 +456,10 @@
}
}

if (options.generatePreloadJsList) {
fs.outputFileSync(ps.join(options.out, 'engine-js-list.json'), JSON.stringify(outputJSFileNames, undefined, 2));
}

Object.assign(result.exports, validEntryChunks);

result.dependencyGraph = {};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { babel as Transformer } from '@ccbuild/transformer';
import babel = Transformer.core;

import { rollup as Bundler } from '@ccbuild/bundler';
import rollup = Bundler.core;

interface Options {
name: string;
}

function toNamedRegister(
{ types }: typeof babel,
options: Options,
): babel.PluginObj {
// options.name 为上面代码传递进来的 chunkId
if (!options || !options.name) {
throw new Error('\'name\' options is required.');
}

return {
visitor: {
CallExpression: (path): void => {
if (types.isMemberExpression(path.node.callee) &&
types.isIdentifier(path.node.callee.object) && path.node.callee.object.name === 'System' &&
types.isIdentifier(path.node.callee.property) && path.node.callee.property.name === 'register' &&
path.node.arguments.length === 2) {
// 当发现 System.register([], function (exports, module) {}); 的时候,插入当前 chunk 的名称,变为:
// System.register('my_chunk_name', [], function (exports, module) {});
path.node.arguments.unshift(types.stringLiteral(options.name));
}
},
},
};
}

function getChunkUrl(chunk: rollup.RenderedChunk): string {
return `cocos-js/${chunk.fileName}`;
}

type RenderChunkResult = { code: string; map?: rollup.SourceMapInput } | string | null | undefined;

export function rpNamedChunk(): rollup.Plugin {
return {
name: 'named-chunk',
renderChunk: async function(this, code, chunk, options): Promise<RenderChunkResult> {

Check warning on line 45 in modules/build-engine/src/engine-js/rollup-plugins/systemjs-named-register-plugin.ts

View workflow job for this annotation

GitHub Actions / test

'options' is defined but never used

const chunkId = getChunkUrl(chunk);
// 这里输入为 System.register([], function(){...}); 格式的 code
// 输出的 transformResult.code 为 System.register('chunk_id', [], function(){...}); 格式
const transformResult = await babel.transformAsync(code, {
sourceMaps: true, // 这里需要强制为 true 吗?
compact: false,
plugins: [[toNamedRegister, { name: chunkId }]],
});
if (!transformResult) {
this.warn('Failed to render chunk.');
return null;
}
return {
code: transformResult.code!,
map: transformResult.map,
};
},
};
}
5 changes: 5 additions & 0 deletions modules/build-engine/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import fs from 'fs-extra';
import { buildTsEngine } from './engine-ts';

function verifyCache (options: buildEngine.Options): boolean {

Check warning on line 7 in modules/build-engine/src/index.ts

View workflow job for this annotation

GitHub Actions / test

'options' is defined but never used
// TODO
return false;
}
Expand Down Expand Up @@ -202,6 +202,11 @@
// * Whether force SUPPORT_JIT to the specified value.
// */
// forceJitValue?: boolean,

/**
* Whether to generate a json file that contains all output script file paths.
*/
generatePreloadJsList?: boolean;
}

export interface Result {
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cocos/ccbuild",
"version": "2.2.3",
"version": "2.2.4",
"description": "The next generation of build tool for Cocos engine.",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
Expand Down
Loading