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

[FEATURE]: New Frontend Static Auditor - Bundle Analyze #119

Open
helabenkhalfallah opened this issue Feb 12, 2025 · 2 comments
Open

[FEATURE]: New Frontend Static Auditor - Bundle Analyze #119

helabenkhalfallah opened this issue Feb 12, 2025 · 2 comments
Labels
enhancement New feature or request WIP Work in progress

Comments

@helabenkhalfallah
Copy link
Member

helabenkhalfallah commented Feb 12, 2025

✨ Description

Extends the static auditor to add "Bundle Analyze".
https://github.com/ekino/v6y/tree/main/v6y-apps/bfb-static-auditor/src/auditors

The bundle analyze provide stats about the dist that will be delivered to the prod.

  1. We should add new auditor: bundle-analyzer

  2. Starting from the worskpace (where code is checkout to be analyzed):

const startAuditorAnalysis = async ({ applicationId, workspaceFolder }: AuditCommonsType) => {

We should launch npm or pnpm or yarn install according to project configuration.

package-lock=> npm
yarn.lock => yarn
pnpm.lock => pnpm
  1. We should find frontend modules:
    -> a frontend module should have a package.json that contains react as dependency (for example).
    -> for each frontend module we should identify which bundler is used: webpack, vite, rspack, next, ...
    -> for each type of bundler we should execute a bundle analyze script: npm run ....
    https://medium.com/ekino-france/rspack-an-engineers-approach-to-build-system-innovation-924e57c596a0
    https://medium.com/ekino-france/beyond-webpack-esbuild-vite-rollup-swc-and-snowpack-97911a7175cf

  2. Once we have stats of bundle and chuncks size:
    -> if a chunck has a size < 600KO Gzip -> it's assumed good
    -> else an error with an exception should be trigerred.

https://www.npmjs.com/package/vite-bundle-visualizer

webpack --profile --json > stats.json
@helabenkhalfallah helabenkhalfallah added the enhancement New feature or request label Feb 12, 2025
@helabenkhalfallah helabenkhalfallah changed the title [FEATURE]: Project Bundle Analyze [FEATURE]: New Frontend Static Auditor - Bundle Analyze Feb 12, 2025
@helabenkhalfallah
Copy link
Member Author

helabenkhalfallah commented Feb 17, 2025

  1. Inside static-analyze create new folder: bundle-analyzer
  2. inside bundle-analyzer we create BundleAnalyzeAuditor and BundleAnalyzeUtils
  3. create the analyze start function:
const startAuditorAnalysis = async ({ applicationId, workspaceFolder }: AuditCommonsType) => {
  1. Inside workers of static-analyze, create BundleAnalyzeWorker like DependenciesAnalysisWorker.
  2. BundleAnalyzeWorker should call startAuditorAnalysis of BundleAnalyzeAuditor.
  3. BundleAnalyzeWorker should be called inside StaticAuditorManager:
        await forkWorker('./src/workers/BundleAnalyzeWorker.ts', workerConfig);
        AppLogger.info(
            '[StaticAuditorManager - startStaticAudit] Bundle Analyze Audit have completed successfully.',
        );
  1. We back to startAuditorAnalysis to analyze bundle:
    -> start by logging the content of workspaceFolder (is the path to current branch source code).
    -> identify which package manager did the source code use (npm or pnpm or yarn).
    https://github.com/egoist/detect-package-manager#readme

-> The result should take on account: simple folder and nested folders (monorepo)

  1. Once the package manager is identified, launch:
npm install or pnpm install or yarn install

At this level we have all needed modules to start building frontends.

  1. Identify only frontend modules (an array that can contains 1 -> n modules).
    -> a frontend module is a node module that contains package.json + react in its dependencies.

  2. Log the list of frontends modules + try to add unit tests to validate different use cases of projects organisations.

  3. For each frontend module, identify the used bundler: webpack, vite, rspack or nextJS.

  4. Once the bundler is identified, start bundle analysis with JSON format as output.

  5. Check the json output and verify that all chuncks have a size < 600 KB in gzipped mode.

Each step should correspond to a commit if possible and try to validate each step with a unit test if possible.

@helabenkhalfallah helabenkhalfallah added the WIP Work in progress label Feb 27, 2025
@helabenkhalfallah
Copy link
Member Author

Code Draft:

import AppLogger from '@v6y/core-logic/src/core/AppLogger.js';
import path from 'path';

const isFrontend = (module) => {
    /// if dependencies react ou angular
};

const getFrontendBundler = (dependencies) => {
    // vite, webpack, next
};

const isBundleChunckConform = ({ name, size }) => {
    // if size > 600kb
    // if name is not hashed
};

const getFrontendDirectories = (directory, frontendModules) => {
    try {
        const files = fs.readdirSync(directory);

        frontendModules = frontendModules || [];

        files.forEach(function (module) {
            if (fs.statSync(directory + '/' + module).isDirectory()) {
                const directoryFiles = fs.readdirSync(module);
                if (directoryFiles?.includes('package.json') && isFrontend(module)) {
                    frontendModules.push(path.join(directory, module));
                } else {
                    frontendModules = getFrontendDirectories(
                        directory + '/' + file,
                        frontendModules,
                    );
                }
            }
        });

        return frontendModules;
    } catch (error) {
        AppLogger.info(`[AuditUtils - getFilesRecursively] error:  ${error}`);
        return [];
    }
};

const analyzeBundle = (workspaceFolder) => {
    const frontendModules = getFrontendDirectories(workspaceFolder);
    for (const module in frontendModules) {
        const packageManger = detect();
        execSync(`${packageManger} install`, { cwd: module });

        const frontendBundler = getFrontendBundler('');
        // vite: pnpm analyze
        // webpack: ....
        // next: pnpm ANALYZE=true pnpm build
        const outputAnalyze = execSync('commande analyze');

        if (isBundleChunckConform(outputAnalyze)) {
            // audit report
        } else {
            // audit report
        }
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request WIP Work in progress
Projects
None yet
Development

No branches or pull requests

1 participant