You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular+Django BFF单项目从Webpack迁移至Angular-CLI的技术咨询

Generating webpack-stats.json when migrating from Webpack to Angular CLI (for Django BFF)

Since Angular CLI doesn’t include a built-in equivalent to webpack-bundle-tracker, we have two practical approaches to replicate that webpack-stats.json output you need for your Django backend integration. Here’s how to implement them:


Approach 1: Post-Build Script (Simplest & Quickest)

This method runs a small Node.js script right after your Angular build completes to generate the stats file in the format you’re used to.

Step 1: Create the stats generation script

Make a file named generate-stats.js in your project root:

const fs = require('fs');
const path = require('path');

// Replace with your Angular project's dist directory path
const distPath = path.join(__dirname, 'dist', 'your-project-name');
// Path where you want the stats file to be saved (matches your old webpack config)
const statsOutputPath = path.join(__dirname, 'assets', 'webpack-stats.json');

// Find the app bundle file (app-*.js) in the dist folder
const distFiles = fs.readdirSync(distPath);
const appBundle = distFiles.find(file => file.startsWith('app-') && file.endsWith('.js'));

if (!appBundle) {
  console.error('Error: Could not locate the app bundle in the dist directory');
  process.exit(1);
}

// Build the stats object to match webpack-bundle-tracker's output format
const statsData = {
  status: 'done',
  chunks: {
    app: [
      {
        name: appBundle,
        publicPath: '/assets/' // Update this to match your Django static file URL
      }
    ]
  }
};

// Ensure the assets directory exists before writing the file
fs.mkdirSync(path.dirname(statsOutputPath), { recursive: true });

// Write the stats file
fs.writeFileSync(statsOutputPath, JSON.stringify(statsData, null, 2));
console.log(`Successfully generated webpack-stats.json at ${statsOutputPath}`);

Step 2: Update your package.json scripts

Modify your package.json to run the script automatically after builds:

{
  "scripts": {
    "build": "ng build && node generate-stats.js",
    "build:prod": "ng build --configuration production && node generate-stats.js"
  }
}

Approach 2: Custom Angular Builder (More Integrated)

If you want a seamless integration with Angular CLI’s build pipeline, create a custom builder that generates the stats file during the build process.

Step 1: Install required dependencies

npm install @angular-devkit/architect @angular-devkit/core --save-dev

Step 2: Create the custom builder

Make a directory builders/generate-stats and add an index.js file:

const { BuilderOutput, createBuilder } = require('@angular-devkit/architect');
const fs = require('fs');
const path = require('path');

async function buildWithStats(options, context) {
  // First run the default Angular build
  const buildTarget = await context.scheduleTarget({
    target: 'build',
    project: context.target.project,
    configuration: context.target.configuration
  });
  const buildResult = await buildTarget.result;

  if (!buildResult.success) {
    return buildResult;
  }

  // Generate the stats file
  const distPath = path.join(context.workspaceRoot, options.outputPath);
  const statsOutputPath = path.join(context.workspaceRoot, options.statsOutputPath);
  
  const distFiles = fs.readdirSync(distPath);
  const appBundle = distFiles.find(file => file.startsWith('app-') && file.endsWith('.js'));

  if (!appBundle) {
    return { success: false, error: 'Failed to locate app bundle in dist directory' };
  }

  const statsData = {
    status: 'done',
    chunks: {
      app: [
        {
          name: appBundle,
          publicPath: options.publicPath
        }
      ]
    }
  };

  fs.mkdirSync(path.dirname(statsOutputPath), { recursive: true });
  fs.writeFileSync(statsOutputPath, JSON.stringify(statsData, null, 2));
  
  context.logger.info(`Generated webpack-stats.json at ${statsOutputPath}`);
  return { success: true };
}

module.exports = createBuilder(buildWithStats);

Step 3: Register the builder in angular.json

Update your angular.json to add the custom builder configuration:

{
  "projects": {
    "your-project-name": {
      "architect": {
        "build-with-stats": {
          "builder": "./builders/generate-stats:build",
          "options": {
            "outputPath": "dist/your-project-name",
            "statsOutputPath": "assets/webpack-stats.json",
            "publicPath": "/assets/"
          },
          "configurations": {
            "production": {
              "outputPath": "dist/your-project-name/production"
            }
          }
        }
      }
    }
  }
}

Step 4: Use the custom builder in package.json

{
  "scripts": {
    "build": "ng run your-project-name:build-with-stats",
    "build:prod": "ng run your-project-name:build-with-stats --configuration production"
  }
}

Key Notes

  • Adjust the publicPath value to match your Django static file serving URL.
  • If you have additional chunks (like vendor or style bundles), extend the scripts to include those in the chunks object of the stats file.
  • Both approaches automatically handle the content hashes Angular CLI adds to filenames in production builds.

内容的提问来源于stack exchange,提问作者sourabh kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:35:30