Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid unused assets Angular

From the documentation I can see that Angular copies the assets/ dir as-is. So, I was wondering if there's a way to avoid that behaviour, and only copying the assets that are actually used somewhere in my application.

I've seen projects (webpack, though not Angular) that have the following config:

{
  test: /\.html$/,
  use: [
    {
      loader: 'html-loader',
      options: {
        minimize: true,
        attrs: ['img:src', 'video:poster', 'source:src']
      }
    }
  ]
},
{
  test: /\.(png|jpg|svg|gif|webm|mp4|ttf|eot|woff|woff2)$/,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[path][name].[hash].[ext]',
        context: 'src'
      },
    },
  ],
},

This only copies the assets that are present in an HTML file.

Can this be achieved in an Angular project?

like image 502
JPYamamoto Avatar asked Aug 14 '26 13:08

JPYamamoto


1 Answers

Currently, there is no way of doing this with Angular 13 out of the box.

However, you could write an angular builder or add a postbuild script to your package.json

Assuming you're adding a postbuild script:

Read the relevant files in your project and write a function to search for the asset paths:

fs.readdir(dirname, function(err, filenames) {
   filenames.forEach(function(filename) {
     fs.readFile(dirname + filename, 'utf-8', function(err, content) {
       const inUse = searchForAssetUse(filename, content);
       if(!inUse) fs.unlinkSync(dirname + filename) //remove the file if it's not in use
     });
   });
 }); 

That way you only bundle assets that are in use in your project. You can add the script to your package.json

Note the postbuild script will run after the build script automatically

"scripts": {
    "build": "ng run project:prerender",
    "postbuild": "node cleanAssets.js"
    ...
}
like image 81
Ryan Eghrari Avatar answered Aug 16 '26 04:08

Ryan Eghrari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!