This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

How to inspect files packaged by webpack before they are emitted


I just lately had a necessity to examine recordsdata in my front-end challenge which can be packaged by webpack earlier than they had been emitted. In my pursuit to perform this a sublime and strong method, I got here throughout webpack hooks that are an exceedingly highly effective approach to faucet into the interior workings of webpack.



What’s webpack?

webpack is a module bundler for JavaScript. Entrance-end functions include many forms of property reminiscent of JavaScript, (HOPEFULLY) Typescript, JSON, HTML, CSS, and pictures. webpack (after you have configure it to course of recordsdata in a sure method) will generate static property, representing your functions modules in order that they are often interpreted by a browser.



What are webpack hooks?

A “hook” in software program growth is an place in code that permits you to faucet right into a module to both present totally different conduct or to react when one thing occurs. webpack offers the next forms of hooks:



How about an instance?

For an instance state of affairs, let’s faux we wish to make it possible for, once we construct our utility, no file is outputted that comprises the string MY_SUPER_SECRET. Maybe we wish to do that to supply a final line of protection from a developer together with a delicate worth in our code and we wish to forestall webpack from even compiling it. If that string is detected, we wish wepback to:

  • throw an error.
  • not emit any recordsdata at any level through the construct.

To do that, let us take a look at the (shouldEmit)[https://webpack.js.org/api/compiler-hooks/#shouldemit] compiler hook. This hook known as earlier than property are emitted and can permit us to error out and never emit property if our validation fails.

To begin, let’s create a brand new plugin class and add it to the plugins block of our webpack.config:

// src/webpack.config.ts
import { AssetValidatorPlugin } from './plugins/asset-validator-plugin';

module.exports= {
    entry: {...},
    module:{...},
    plugins: [
        new AssetValidatorPlugin(),
        ...
    ]
};
Enter fullscreen mode

Exit fullscreen mode

Observe that, whereas I’ve outlined my plugin in a separate class/file, you might embody it in your webpack.config inline.

Now, let’s check out the plugin:

// src/plugins/asset-validator-plugin.ts
import * as webpack from 'webpack';

export class AssetValidatorPlugin {
  apply(compiler: webpack.Compiler) {
    compiler.hooks.shouldEmit.faucet('AssetValidatorPlugin', (compilation: webpack.compilation.Compilation) => {
      this.validateAssets(compilation);
    });
  }

  public validateAssets(compilation: webpack.compilation.Compilation) {
    const property = Object.entries(compilation.property);
    const regex = new RegExp('MY_SUPER_SECRET', 'g');

    // Loop by means of every asset and examine to see if it comprises any delicate strings
    for (let i = 0; i < property.size; i++) {
      const [fileName] = property[i];
      const asset = compilation.getAsset(fileName);
      const supply = asset.supply.supply();
      const contents = convertSourceToString(supply);
      const matches = contents.match(regex);

      if (matches) {
        throw new Error(
          "Our software has recognized the presence of the string 'MY_SUPER_SECRET' in your compiled code. Compilation has been aborted."
        );
      }
    }

    return true;
  }
}

// This perform is barely wanted as a result of asset.supply.supply() could be a string or ArrayBuffer
const convertSourceToString = (supply: string | ArrayBuffer): string => {
  if (typeof supply === 'string') {
    return supply;
  } else {
    return new TextDecoder().decode(supply);
  }
};
Enter fullscreen mode

Exit fullscreen mode

So, let’s assessment what’s included our plugin. We have outlined our plugin class and, inside, are in a position to tap into the compiler.hooks.shouldEmit hook. Within the hook callback, we merely name a validateAssets() perform we have outlined which loops by means of all property which can be a part of the compilation and use common expression matching to see if the string exists. We throw an error if it does, short-circuiting the compilation and never emitting any recordsdata. If it does not include our particular string, we’ll return true, compilation will proceed, emitting the packaged recordsdata as anticipated.

When you have a must cross any parameters to your plugin, that may simply be achieved by defining a constructor in your plugin class like this:

constructor(choices: MyPluginOptions) {
    this.choices = choices;
}
Enter fullscreen mode

Exit fullscreen mode



Conclusion

Hopefully you now have a greater understanding of webpack hooks and how one can leverage them to supply extra conduct when your utility’s property are packaged.

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?