All files external.ts

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

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                                                                                                                                                           
import type {
    Compiler,
    ExternalItem,
    ExternalItemFunctionData
} from '@rspack/core';
import type { ParsedModuleLinkPluginOptions } from './types';
 
export function initExternal(
    compiler: Compiler,
    opts: ParsedModuleLinkPluginOptions
) {
    const externals: ExternalItem[] = [];
    if (Array.isArray(compiler.options.externals)) {
        externals.push(...compiler.options.externals);
    } else if (compiler.options.externals) {
        externals.push(compiler.options.externals);
    }
 
    const defaultContext = compiler.options.context ?? process.cwd();
 
    const importMap = new Map<string, string>();
    externals.push(async (data: ExternalItemFunctionData) => {
        if (!data.request || !data.context || !data.contextInfo?.issuer) return;
 
        if (importMap.size === 0) {
            await Promise.all(
                Object.values(opts.exports).map(async (value) => {
                    const identifier = value.rewrite
                        ? value.identifier
                        : value.name;
                    importMap.set(identifier, identifier);
                    const entry = await resolvePath(
                        data,
                        defaultContext,
                        value.file
                    );
                    if (entry) {
                        importMap.set(entry, identifier);
                    }
                })
            );
            for (const key of Object.keys(opts.imports)) {
                importMap.set(key, key);
            }
        }
        // 1、先按照标识符查找
        let importName = importMap.get(data.request);
        if (!importName) {
            // 2、再按照路径查找
            const result = await resolvePath(data, data.context, data.request);
            if (result) {
                importName = importMap.get(result);
            }
        }
 
        if (importName) {
            return `module-import ${importName}`;
        }
    });
    compiler.options.externals = externals;
}
 
async function resolvePath(
    data: ExternalItemFunctionData,
    context: string,
    request: string
): Promise<string | null> {
    return new Promise((resolve) => {
        if (data.getResolve) {
            data.getResolve()(context, request, (err, res) => {
                resolve(res ? res : null);
            });
        } else {
            resolve(null);
        }
    });
}