All files / src/module-link manifest-plugin.ts

0% Statements 0/152
100% Branches 1/1
100% Functions 1/1
0% Lines 0/152

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180                                                                                                                                                                                                                                                                                                                                                                       
import type { Compilation, Compiler, StatsCompilation } from '@rspack/core';
import upath from 'upath';
import type {
    ManifestJson,
    ManifestJsonChunks,
    ManifestJsonExports,
    ParsedModuleLinkPluginOptions
} from './types';
 
export const RSPACK_PLUGIN_NAME = 'rspack-module-link-plugin';
 
export class ManifestPlugin {
    constructor(private opts: ParsedModuleLinkPluginOptions) {}
 
    apply(compiler: Compiler) {
        const opts = this.opts;
        const { Compilation } = compiler.rspack;
        compiler.hooks.thisCompilation.tap(
            RSPACK_PLUGIN_NAME,
            (compilation) => {
                let manifestJson: ManifestJson = {
                    name: opts.name,
                    exports: {},
                    scopes: opts.scopes,
                    files: [],
                    chunks: {}
                };
 
                compilation.hooks.processAssets.tap(
                    {
                        name: RSPACK_PLUGIN_NAME,
                        stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
                    },
                    (assets) => {
                        const stats = compilation.getStats().toJson({
                            hash: true,
                            entrypoints: true
                        });
 
                        const exports = getExports(opts, stats);
                        const resources = Object.keys(assets)
                            .map(transFileName)
                            .filter((file) => !file.includes('hot-update'));
                        manifestJson = {
                            name: opts.name,
                            exports: exports,
                            scopes: opts.scopes,
                            files: resources,
                            chunks: getChunks(opts, compilation)
                        };
                        const { RawSource } = compiler.rspack.sources;
 
                        compilation.emitAsset(
                            'manifest.json',
                            new RawSource(JSON.stringify(manifestJson, null, 4))
                        );
                    }
                );
 
                if (opts.injectChunkName) {
                    compilation.hooks.processAssets.tap(
                        {
                            name: RSPACK_PLUGIN_NAME,
                            stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
                        },
                        (assets) => {
                            const { RawSource } = compiler.rspack.sources;
                            for (const [key, value] of Object.entries(
                                manifestJson.chunks
                            )) {
                                const asset = assets[value.js];
                                if (!asset) {
                                    return;
                                }
                                const source = new RawSource(
                                    `import.meta.chunkName = import.meta.chunkName ?? ${JSON.stringify(key)};\n${asset.source()}`
                                );
 
                                compilation.updateAsset(value.js, source);
                            }
                        }
                    );
                }
            }
        );
    }
}
 
function transFileName(fileName: string): string {
    return fileName.replace(/^.\//, '');
}
 
export function getExports(
    opts: ParsedModuleLinkPluginOptions,
    stats: StatsCompilation
): ManifestJsonExports {
    const entrypoints = stats.entrypoints || {};
    const exports: ManifestJsonExports = {};
    for (const [key, value] of Object.entries(entrypoints)) {
        const asset = value.assets?.find((item) => {
            return (
                item.name.endsWith(opts.ext) &&
                item.name.startsWith(key) &&
                !item.name.includes('hot-update')
            );
        });
        if (!asset) continue;
        if (key in opts.exports) {
            exports[key] = {
                ...opts.exports[key],
                file: asset.name
            };
        }
    }
    return exports;
}
 
function getChunks(
    opts: ParsedModuleLinkPluginOptions,
    compilation: Compilation
) {
    const stats = compilation.getStats().toJson({
        all: false,
        chunks: true,
        modules: true,
        chunkModules: true,
        ids: true
    });
    const buildChunks: ManifestJsonChunks = {};
    if (!stats.chunks) return buildChunks;
 
    for (const chunk of stats.chunks) {
        const module = chunk.modules
            ?.sort((a, b) => {
                return (a.index ?? -1) - (b?.index ?? -1);
            })
            ?.find((module) => {
                return module.moduleType?.includes('javascript/');
            });
        if (!module?.nameForCondition) continue;
 
        const js = chunk.files?.find((file) => file.endsWith(opts.ext));
        if (!js) continue;
 
        const root = compilation.options.context ?? process.cwd();
        const name = generateIdentifier({
            root,
            name: opts.name,
            filePath: module.nameForCondition
        });
 
        const css = chunk.files?.filter((file) => file.endsWith('.css')) ?? [];
        const resources = chunk.auxiliaryFiles ?? [];
        buildChunks[name] = {
            name,
            js,
            css,
            resources
        };
    }
    return buildChunks;
}
 
export function generateIdentifier({
    root,
    name,
    filePath
}: {
    root: string;
    name: string;
    filePath: string;
}) {
    const unixFilePath = upath.toUnix(filePath);
    if (!root) {
        return `${name}@${unixFilePath}`;
    }
    const file = upath.relative(upath.toUnix(root), unixFilePath);
    return `${name}@${file}`;
}